Example #1
0
 public function draw()
 {
     $start = 3;
     foreach ($this->tabs as $i => $tab) {
         $attrs = NCURSES_A_UNDERLINE;
         ncurses_wmove($this->window, 0, $start);
         //            ncurses_wvline($this->window, NCURSES_A_NORMAL, 1);
         if ($i === $this->active) {
             $attrs += NCURSES_A_REVERSE;
         }
         if ($tab->hasAlert()) {
             ncurses_wcolor_set($this->window, 0);
         }
         if ($attrs) {
             ncurses_wattron($this->window, $attrs);
         }
         $tabName = sprintf("[F%d] %s", $i + 1, $tab->name);
         ncurses_mvwaddstr($this->window, 0, $start + 1, $tabName);
         if ($attrs) {
             ncurses_wattroff($this->window, $attrs);
         }
         //            ncurses_wvline($this->window, NCURSES_A_NORMAL, 1);
         $start += strlen($tabName) + 3;
         if ($i === $this->active) {
             $tab->draw();
             ncurses_top_panel($tab->panel->panel);
         }
     }
 }
Example #2
0
 /**
  * Draw list items
  *
  * @param null $current
  *
  * @internal param int $select
  * @return void
  */
 public function drawList($current = null)
 {
     $current = $this->current;
     // Current more than last visible item
     if ($current > $this->firstPos + $this->getMaxY() && count($this->items) > $current) {
         $this->firstPos = $current;
     }
     if ($this->getMaxY() > count($this->items)) {
         $lastPos = count($this->items);
     } else {
         $lastPos = $this->firstPos + $this->getMaxY();
     }
     for ($i = $this->firstPos; $i < $lastPos; $i++) {
         $attrs = 0;
         $item = $this->items[$i];
         if ($i === $current) {
             $attrs += NCURSES_A_REVERSE;
         }
         if (isset($item['bold']) && $item['bold']) {
             $attrs += NCURSES_A_BOLD;
         }
         if ($attrs) {
             ncurses_wattron($this->getWindow(), $attrs);
         }
         $title = str_pad($item['title'], $this->getMaxX() - 2, ' ');
         ncurses_mvwaddstr($this->getWindow(), $i + 1, 1, $title);
         if ($attrs) {
             ncurses_wattroff($this->getWindow(), $attrs);
         }
     }
 }
Example #3
0
 public function setTitle($title)
 {
     $this->border();
     ncurses_wattron($this->getWindow(), NCURSES_A_REVERSE);
     ncurses_mvwaddstr($this->window, 0, 2, $title);
     ncurses_wattroff($this->getWindow(), NCURSES_A_REVERSE);
 }
Example #4
0
 public function title($text)
 {
     ncurses_wborder($this->resource, 0, 0, 0, 0, 0, 0, 0, 0);
     ncurses_wattron($this->resource, NCURSES_A_REVERSE);
     ncurses_mvwaddstr($this->resource, 0, 2, '[' . $text . ']');
     ncurses_wattroff($this->resource, NCURSES_A_REVERSE);
 }
 /**
  * {@inheritdoc}
  */
 protected function render()
 {
     foreach ($this->varList as $name => $var) {
         ncurses_wattron($this->getPadResource(), NCURSES_A_BOLD);
         $this->printText("<<4>>{$name} ▸\n");
         ncurses_wattroff($this->getPadResource(), NCURSES_A_BOLD);
     }
 }
Example #6
0
 /**
  * Construct
  */
 public function start()
 {
     ncurses_keypad($this->getWindow(), true);
     ncurses_noecho();
     $this->setBorder();
     ncurses_wattron($this->getWindow(), NCURSES_A_BOLD);
     ncurses_mvwaddstr($this->getWindow(), 0, 1, $this->title);
     ncurses_wattroff($this->getWindow(), NCURSES_A_BOLD);
     ncurses_mvwaddstr($this->getWindow(), 2, 2, $this->text);
     $this->processing();
 }
 /**
  * {@inheritdoc}
  */
 protected function render()
 {
     foreach ($this->constants as $cat => $values) {
         // retrieve current position
         $x = null;
         $y = null;
         ncurses_getyx($this->getPadResource(), $y, $x);
         // category name
         ncurses_wattron($this->getPadResource(), NCURSES_A_BOLD);
         $catText = $this->isElementExpanded($cat) ? "{$cat} ▾" : "{$cat} ▸";
         $this->printText("<<4>>{$catText}\n");
         ncurses_wattroff($this->getPadResource(), NCURSES_A_BOLD);
         $this->setExpandableElementPositionY($cat, $y);
         if (!$this->isElementExpanded($cat)) {
             continue;
         }
         // category constants
         if (!empty($values)) {
             $maxLength = 0;
             foreach ($values as $name => $value) {
                 $maxLength = max($maxLength, strlen($name));
             }
             foreach ($values as $name => $value) {
                 $name = str_pad($name, $maxLength, " ", STR_PAD_RIGHT);
                 switch (gettype($value)) {
                     case "string":
                         $value = str_replace(array("\n", "\r", "\t"), array("\\n", "\\r", "\\t"), $value);
                         break;
                     case "bool":
                     case "boolean":
                         $value = $value ? "true" : "false";
                         $value = "<<2>>{$value}";
                         break;
                     case "null":
                     case "NULL":
                         $value = "<<2>>null";
                         break;
                 }
                 $this->printText("    <<3>>{$name} : <<0>>{$value}\n");
             }
         } else {
             // no constants
             $this->_firePhp->log("* empty *");
         }
     }
 }
Example #8
0
 /**
  *
  */
 function draw($workspace)
 {
     $wh = $this->_wh;
     ncurses_wcolor_set($wh, NCC_FRAME);
     ncurses_wborder($wh, 0, 0, 0, 0, 0, 0, 0, 0);
     ncurses_wcolor_set($wh, NCC_TITLE);
     ncurses_wattron($wh, NCURSES_A_BOLD);
     $left = floor(($this->_w - 2) / 2 - (strlen($this->_title) + 2) / 2);
     ncurses_mvwaddstr($wh, 0, $left, ' ' . $this->_title . ' ');
     ncurses_wattroff($wh, NCURSES_A_BOLD);
     ncurses_wcolor_set($wh, NCC_TEXT);
     for ($n = 0; $n < $this->_h - 2; $n++) {
         ncurses_mvwaddstr($wh, $n + 1, 1, str_repeat(" ", $this->_w - 2));
     }
     ncurses_wrefresh($wh);
     ncurses_wcolor_set($wh, 0);
     ncurses_move(-1, 1);
     ncurses_refresh();
 }
 /**
  * {@inheritdoc}
  */
 protected function render()
 {
     if (null === $this->profilerManager || 0 == count($this->profilerManager)) {
         return;
     }
     $this->profileParamsList = array();
     foreach ($this->profilerManager as $idProfiler => $profiler) {
         // retrieve current position
         $x = null;
         $y = null;
         ncurses_getyx($this->getPadResource(), $y, $x);
         // print profiler name and total execution time for that profiler
         $totalTime = count($profiler) ? $profiler->getTotalElapsedSecs() : 0;
         $totalTime = number_format($totalTime, 4, ".", " ");
         $title = $profiler->getProfilerName() . " <<5>>(total execution time : {$totalTime} s)";
         $symbol = $this->isElementExpanded($idProfiler) ? "▾" : "▸";
         ncurses_wattron($this->getPadResource(), NCURSES_A_BOLD);
         $this->printText("<<4>>{$title} <<4>>{$symbol}\n");
         ncurses_wattroff($this->getPadResource(), NCURSES_A_BOLD);
         $this->setExpandableElementPositionY($idProfiler, $y);
         if (!$this->isElementExpanded($idProfiler)) {
             continue;
         }
         // print profiles
         if (count($profiler)) {
             foreach ($profiler as $i => $profile) {
                 $funcName = $profile->getCallingFunction();
                 $file = $profile->getCallingFile();
                 $line = $profile->getCallingLine();
                 $comment = $profile->getComment();
                 $this->printText("    ");
                 ncurses_wattron($this->getPadResource(), NCURSES_A_REVERSE);
                 $this->printText("<<6>>#{$i} {$funcName}\n");
                 ncurses_wattroff($this->getPadResource(), NCURSES_A_REVERSE);
                 // base infos
                 $this->printText("        <<2>>Start file : <<0>>{$file}\n");
                 $this->printText("        <<2>>Start line : <<0>>{$line}\n");
                 if ($comment) {
                     $this->printText("        <<2>>Comment    : <<0>>{$comment}\n");
                 }
                 $this->printText(" \n");
                 // args
                 $x = null;
                 $y = null;
                 ncurses_getyx($this->getPadResource(), $y, $x);
                 $this->printText("        <<4>>Params ▸\n");
                 $this->printText(" \n");
                 $this->profileParamsList[$y] = $profile->getParams();
                 // query stats
                 $startTime = $profile->getStartMicrotime() - $this->startMicrotime;
                 $endTime = $profile->getEndMicrotime() ? $profile->getEndMicrotime() - $this->startMicrotime : 0;
                 $profileTime = $this->formatQueryTime($startTime, $endTime);
                 $startMemory = $profile->getStartMemoryUsage(true);
                 $endMemory = $profile->getEndMemoryUsage(true);
                 $startPeakMemory = $profile->getStartPeakMemoryUsage(true);
                 $endPeakMemory = $profile->getEndPeakMemoryUsage(true);
                 $profileMemory = $this->formatQueryMemory($startMemory, $endMemory, "Memory usage");
                 $profilePeakMemory = $this->formatQueryMemory($startPeakMemory, $endPeakMemory, "Memory peak usage");
                 $profileStats = array("{$profileTime[0]} | {$profileMemory[0]} | {$profilePeakMemory[0]}", "{$profileTime[1]} | {$profileMemory[1]} | {$profilePeakMemory[1]}", "{$profileTime[2]} | {$profileMemory[2]} | {$profilePeakMemory[2]}", "{$profileTime[3]} |");
                 foreach ($profileStats as $statLine) {
                     $this->printText("        {$statLine}\n");
                 }
                 $this->printText(" \n");
                 // stack trace
                 $stackTrace = $profile->getCallingTrace();
                 $num = count($stackTrace) - 1;
                 $numLength = strlen($num);
                 foreach ($stackTrace as $event) {
                     $numString = str_pad($num, $numLength, "0", STR_PAD_LEFT);
                     $this->printText("        <<0>>#{$numString} <<1>>{$event['func']}\n");
                     $this->printText("            <<2>>File :<<0>> {$event['file']}\n");
                     $this->printText("            <<2>>Line :<<0>> {$event['line']}\n");
                     $this->printText(" \n");
                     $num--;
                 }
             }
         }
     }
 }
Example #10
0
 /**
  * Write an individual buffer command to the screen
  *
  * Probably never needs to be called directly
  */
 public function playBufferItem($item)
 {
     // Adjust offset
     $item['y'] -= $this->scrollTop;
     // Skip this item if it's offscreen
     if ($item['y'] < 1) {
         return $this;
     }
     if ($item['y'] >= $this->height - 1) {
         return $this;
     }
     $optionMapping = ['reverse' => NCURSES_A_REVERSE, 'bold' => NCURSES_A_BOLD];
     foreach ($optionMapping as $option => $ncursesAttribute) {
         if (isset($item['options'][$option]) && $item['options'][$option]) {
             ncurses_wattron($this->window, $ncursesAttribute);
         }
     }
     ncurses_mvwaddstr($this->window, $item['y'], $item['x'], $item['str']);
     foreach ($optionMapping as $option => $ncursesAttribute) {
         if (isset($item['options'][$option]) && $item['options'][$option]) {
             ncurses_wattroff($this->window, $ncursesAttribute);
         }
     }
     return $this;
 }
Example #11
0
 /**
  * 
  *
  * @param string $ps_source
  * @param string $ps_mapping
  * @param array $pa_options
  *		user_id = user to execute import for
  *		description = Text describing purpose of import to be logged.
  *		showCLIProgressBar = Show command-line progress bar. Default is false.
  *		format = Format of data being imported. MANDATORY
  *		useNcurses = Use ncurses library to format output
  *		logDirectory = path to directory where logs should be written
  *		logLevel = KLogger constant for minimum log level to record. Default is KLogger::INFO. Constants are, in descending order of shrillness:
  *			KLogger::EMERG = Emergency messages (system is unusable)
  *			KLogger::ALERT = Alert messages (action must be taken immediately)
  *			KLogger::CRIT = Critical conditions
  *			KLogger::ERR = Error conditions
  *			KLogger::WARN = Warnings
  *			KLogger::NOTICE = Notices (normal but significant conditions)
  *			KLogger::INFO = Informational messages
  *			KLogger::DEBUG = Debugging messages
  *		dryRun = do import but don't actually save data
  *		environment = an array of environment values to provide to the import process. The keys manifest themselves as mappable tags.
  *		forceImportForPrimaryKeys = list of primary key ids to force mapped source data into. The number of keys passed should equal or exceed the number of rows in the source data. [Default is empty] 
  *		transaction = transaction to perform import within. Will not be used if noTransaction option is set. [Default is to create a new transaction]
  *		noTransaction = don't wrap the import in a transaction. [Default is false]
  */
 public static function importDataFromSource($ps_source, $ps_mapping, $pa_options = null)
 {
     ca_data_importers::$s_num_import_errors = 0;
     ca_data_importers::$s_num_records_processed = 0;
     ca_data_importers::$s_num_records_skipped = 0;
     ca_data_importers::$s_import_error_list = array();
     $opa_app_plugin_manager = new ApplicationPluginManager();
     $va_notices = $va_errors = array();
     $pb_no_transaction = caGetOption('noTransaction', $pa_options, false, array('castTo' => 'bool'));
     $pa_force_import_for_primary_keys = caGetOption('forceImportForPrimaryKeys', $pa_options, null);
     if (!($t_mapping = ca_data_importers::mappingExists($ps_mapping))) {
         return null;
     }
     $o_event = ca_data_import_events::newEvent(isset($pa_options['user_id']) ? $pa_options['user_id'] : null, $pa_options['format'], $ps_source, isset($pa_options['description']) ? $pa_options['description'] : '');
     $o_trans = null;
     if (!$pb_no_transaction) {
         if (!($o_trans = caGetOption('transaction', $pa_options, null))) {
             $o_trans = new Transaction();
         }
         $t_mapping->setTransaction($o_trans);
     }
     $po_request = caGetOption('request', $pa_options, null);
     $pb_dry_run = caGetOption('dryRun', $pa_options, false);
     $pn_file_number = caGetOption('fileNumber', $pa_options, 0);
     $pn_number_of_files = caGetOption('numberOfFiles', $pa_options, 1);
     $o_config = Configuration::load();
     if (!is_array($pa_options) || !isset($pa_options['logLevel']) || !$pa_options['logLevel']) {
         $pa_options['logLevel'] = KLogger::INFO;
     }
     if (!is_array($pa_options) || !isset($pa_options['logDirectory']) || !$pa_options['logDirectory'] || !file_exists($pa_options['logDirectory'])) {
         if (!($pa_options['logDirectory'] = $o_config->get('batch_metadata_import_log_directory'))) {
             $pa_options['logDirectory'] = ".";
         }
     }
     if (!is_writeable($pa_options['logDirectory'])) {
         $pa_options['logDirectory'] = caGetTempDirPath();
     }
     $o_log = new KLogger($pa_options['logDirectory'], $pa_options['logLevel']);
     $vb_show_cli_progress_bar = isset($pa_options['showCLIProgressBar']) && $pa_options['showCLIProgressBar'] ? true : false;
     $o_progress = caGetOption('progressBar', $pa_options, new ProgressBar('WebUI'));
     if ($vb_show_cli_progress_bar) {
         $o_progress->setMode('CLI');
         $o_progress->set('outputToTerminal', true);
     }
     if ($vb_use_ncurses = isset($pa_options['useNcurses']) && $pa_options['useNcurses'] ? true : false) {
         $vb_use_ncurses = caCLIUseNcurses();
     }
     $vn_error_window_height = null;
     $vn_max_x = $vn_max_y = null;
     if ($vb_use_ncurses) {
         ncurses_init();
         $r_screen = ncurses_newwin(0, 0, 0, 0);
         ncurses_border(0, 0, 0, 0, 0, 0, 0, 0);
         ncurses_getmaxyx($r_screen, $vn_max_y, $vn_max_x);
         $vn_error_window_height = $vn_max_y - 8;
         $r_errors = ncurses_newwin($vn_error_window_height, $vn_max_x - 4, 4, 2);
         ncurses_wborder($r_errors, 0, 0, 0, 0, 0, 0, 0, 0);
         ncurses_wattron($r_errors, NCURSES_A_REVERSE);
         ncurses_mvwaddstr($r_errors, 0, 1, _t(" Recent errors "));
         ncurses_wattroff($r_errors, NCURSES_A_REVERSE);
         $r_progress = ncurses_newwin(3, $vn_max_x - 4, $vn_max_y - 4, 2);
         ncurses_wborder($r_progress, 0, 0, 0, 0, 0, 0, 0, 0);
         ncurses_wattron($r_progress, NCURSES_A_REVERSE);
         ncurses_mvwaddstr($r_progress, 0, 1, _t(" Progress "));
         ncurses_wattroff($r_progress, NCURSES_A_REVERSE);
         $r_status = ncurses_newwin(3, $vn_max_x - 4, 1, 2);
         ncurses_wborder($r_status, 0, 0, 0, 0, 0, 0, 0, 0);
         ncurses_wattron($r_status, NCURSES_A_REVERSE);
         ncurses_mvwaddstr($r_status, 0, 1, _t(" Import status "));
         ncurses_wattroff($r_status, NCURSES_A_REVERSE);
         ncurses_refresh(0);
         ncurses_wrefresh($r_progress);
         ncurses_wrefresh($r_errors);
         ncurses_wrefresh($r_status);
     }
     $o_log->logInfo(_t('Started import of %1 using mapping %2', $ps_source, $t_mapping->get("importer_code")));
     $t = new Timer();
     $vn_start_time = time();
     $va_log_import_error_opts = array('startTime' => $vn_start_time, 'window' => $r_errors, 'log' => $o_log, 'request' => $po_request, 'progressCallback' => isset($pa_options['progressCallback']) && ($ps_callback = $pa_options['progressCallback']) ? $ps_callback : null, 'reportCallback' => isset($pa_options['reportCallback']) && ($ps_callback = $pa_options['reportCallback']) ? $ps_callback : null);
     global $g_ui_locale_id;
     // constant locale set by index.php for web requests
     $vn_locale_id = isset($pa_options['locale_id']) && (int) $pa_options['locale_id'] ? (int) $pa_options['locale_id'] : $g_ui_locale_id;
     $o_dm = $t_mapping->getAppDatamodel();
     $o_progress->start(_t('Reading %1', $ps_source), array('window' => $r_progress));
     if ($po_request && isset($pa_options['progressCallback']) && ($ps_callback = $pa_options['progressCallback'])) {
         $ps_callback($po_request, $pn_file_number, $pn_number_of_files, $ps_source, 0, 100, _t('Reading %1', $ps_source), time() - $vn_start_time, memory_get_usage(true), 0, ca_data_importers::$s_num_import_errors);
     }
     // Open file
     $ps_format = isset($pa_options['format']) && $pa_options['format'] ? $pa_options['format'] : null;
     if (!($o_reader = $t_mapping->getDataReader($ps_source, $ps_format))) {
         ca_data_importers::logImportError(_t("Could not open source %1 (format=%2)", $ps_source, $ps_format), $va_log_import_error_opts);
         if ($vb_use_ncurses) {
             ncurses_end();
         }
         if ($o_trans) {
             $o_trans->rollback();
         }
         return false;
     }
     if (!$o_reader->read($ps_source, array('basePath' => $t_mapping->getSetting('basePath')))) {
         ca_data_importers::logImportError(_t("Could not read source %1 (format=%2)", $ps_source, $ps_format), $va_log_import_error_opts);
         if ($vb_use_ncurses) {
             ncurses_end();
         }
         if ($o_trans) {
             $o_trans->rollback();
         }
         return false;
     }
     $o_log->logDebug(_t('Finished reading input source at %1 seconds', $t->getTime(4)));
     $vn_num_items = $o_reader->numRows();
     $o_progress->setTotal($vn_num_items);
     $o_progress->start(_t('Importing from %1', $ps_source), array('window' => $r_progress));
     if ($po_request && isset($pa_options['progressCallback']) && ($ps_callback = $pa_options['progressCallback'])) {
         $ps_callback($po_request, $pn_file_number, $pn_number_of_files, $ps_source, 0, $vn_num_items, _t('Importing from %1', $ps_source), time() - $vn_start_time, memory_get_usage(true), 0, ca_data_importers::$s_num_import_errors);
     }
     // What are we importing?
     $vn_table_num = $t_mapping->get('table_num');
     if (!($t_subject = $o_dm->getInstanceByTableNum($vn_table_num))) {
         // invalid table
         if ($vb_use_ncurses) {
             ncurses_end();
         }
         if ($o_trans) {
             $o_trans->rollback();
         }
         return false;
     }
     $t_subject->setTransaction($o_trans);
     $vs_subject_table_name = $t_subject->tableName();
     $t_label = $t_subject->getLabelTableInstance();
     $t_label->setTransaction($o_trans);
     $vs_label_display_fld = $t_subject->getLabelDisplayField();
     $vs_subject_table = $t_subject->tableName();
     $vs_type_id_fld = $t_subject->getTypeFieldName();
     $vs_idno_fld = $t_subject->getProperty('ID_NUMBERING_ID_FIELD');
     // get mapping rules
     $va_mapping_rules = $t_mapping->getRules();
     // get mapping groups
     $va_mapping_groups = $t_mapping->getGroups();
     $va_mapping_items = $t_mapping->getItems();
     //
     // Mapping-level settings
     //
     $vs_type_mapping_setting = $t_mapping->getSetting('type');
     $vn_num_initial_rows_to_skip = $t_mapping->getSetting('numInitialRowsToSkip');
     if (!in_array($vs_import_error_policy = $t_mapping->getSetting('errorPolicy'), array('ignore', 'stop'))) {
         $vs_import_error_policy = 'ignore';
     }
     if (!in_array($vs_existing_record_policy = $t_mapping->getSetting('existingRecordPolicy'), array('none', 'skip_on_idno', 'skip_on_preferred_labels', 'merge_on_idno', 'merge_on_preferred_labels', 'merge_on_idno_and_preferred_labels', 'merge_on_idno_with_replace', 'merge_on_preferred_labels_with_replace', 'merge_on_idno_and_preferred_labels_with_replace', 'overwrite_on_idno', 'overwrite_on_preferred_labels', 'overwrite_on_idno_and_preferred_labels'))) {
         $vs_existing_record_policy = 'none';
     }
     // Analyze mapping for figure out where type, idno, preferred label and other mandatory fields are coming from
     $vn_type_id_mapping_item_id = $vn_idno_mapping_item_id = null;
     $va_preferred_label_mapping_ids = array();
     $va_mandatory_field_mapping_ids = array();
     $va_mandatory_fields = $t_subject->getMandatoryFields();
     foreach ($va_mapping_items as $vn_item_id => $va_item) {
         $vs_destination = $va_item['destination'];
         if (sizeof($va_dest_tmp = explode(".", $vs_destination)) >= 2) {
             if ($va_dest_tmp[0] == $vs_subject_table && $va_dest_tmp[1] == 'preferred_labels') {
                 if (isset($va_dest_tmp[2])) {
                     $va_preferred_label_mapping_ids[$vn_item_id] = $va_dest_tmp[2];
                 } else {
                     $va_preferred_label_mapping_ids[$vn_item_id] = $vs_label_display_fld;
                 }
                 continue;
             }
         }
         switch ($vs_destination) {
             case 'representation_id':
                 if ($vs_subject_table == 'ca_representation_annotations') {
                     $vn_type_id_mapping_item_id = $vn_item_id;
                 }
                 break;
             case "{$vs_subject_table}.{$vs_type_id_fld}":
                 $vn_type_id_mapping_item_id = $vn_item_id;
                 break;
             case "{$vs_subject_table}.{$vs_idno_fld}":
                 $vn_idno_mapping_item_id = $vn_item_id;
                 break;
         }
         foreach ($va_mandatory_fields as $vs_mandatory_field) {
             if ($vs_mandatory_field == $vs_type_id_fld) {
                 continue;
             }
             // type is handled separately
             if ($vs_destination == "{$vs_subject_table}.{$vs_mandatory_field}") {
                 $va_mandatory_field_mapping_ids[$vs_mandatory_field] = $vn_item_id;
             }
         }
     }
     $va_items_by_group = array();
     foreach ($va_mapping_items as $vn_item_id => $va_item) {
         $va_items_by_group[$va_item['group_id']][$va_item['item_id']] = $va_item;
     }
     $o_log->logDebug(_t('Finished analyzing mapping at %1 seconds', $t->getTime(4)));
     //
     // Set up environment
     //
     $va_environment = caGetOption('environment', $pa_options, array(), array('castTo' => 'array'));
     if (is_array($va_environment_config = $t_mapping->getEnvironment())) {
         foreach ($va_environment_config as $vn_i => $va_environment_item) {
             $va_env_tmp = explode("|", $va_environment_item['value']);
             if (!($o_env_reader = $t_mapping->getDataReader($ps_source, $ps_format))) {
                 break;
             }
             if (!$o_env_reader->read($ps_source, array('basePath' => ''))) {
                 break;
             }
             $o_env_reader->nextRow();
             switch (sizeof($va_env_tmp)) {
                 case 1:
                     $vs_env_value = $o_env_reader->get($va_environment_item['value'], array('returnAsArray' => false));
                     break;
                 case 2:
                     $vn_seek = (int) $va_env_tmp[0];
                     $o_reader->seek($vn_seek > 0 ? $vn_seek - 1 : $vn_seek);
                     $o_env_reader->nextRow();
                     $vs_env_value = $o_env_reader->get($va_env_tmp[1], array('returnAsArray' => false));
                     $o_reader->seek(0);
                     break;
                 default:
                     $vs_env_value = $va_environment_item['value'];
                     break;
             }
             $va_environment[$va_environment_item['name']] = $vs_env_value;
         }
     }
     //
     // Run through rows
     //
     $vn_row = 0;
     ca_data_importers::$s_num_records_processed = 0;
     while ($o_reader->nextRow()) {
         $va_mandatory_field_values = array();
         $vs_preferred_label_for_log = null;
         if ($vn_row < $vn_num_initial_rows_to_skip) {
             // skip over initial header rows
             $vn_row++;
             continue;
         }
         $vn_row++;
         $t->startTimer();
         $o_log->logDebug(_t('Started reading row %1 at %2 seconds', $vn_row, $t->getTime(4)));
         $t_subject = $o_dm->getInstanceByTableNum($vn_table_num);
         if ($o_trans) {
             $t_subject->setTransaction($o_trans);
         }
         $t_subject->setMode(ACCESS_WRITE);
         // Update status display
         if ($vb_use_ncurses && ca_data_importers::$s_num_records_processed) {
             ncurses_mvwaddstr($r_status, 1, 2, _t("Items processed/skipped: %1/%2", ca_data_importers::$s_num_records_processed, ca_data_importers::$s_num_records_skipped) . str_repeat(" ", 5) . _t("Errors: %1 (%2)", ca_data_importers::$s_num_import_errors, sprintf("%3.1f", ca_data_importers::$s_num_import_errors / ca_data_importers::$s_num_records_processed * 100) . "%") . str_repeat(" ", 6) . _t("Mapping: %1", $ps_mapping) . str_repeat(" ", 5) . _t("Source: %1", $ps_source) . str_repeat(" ", 5) . date("Y-m-d H:i:s") . str_repeat(" ", 5));
             ncurses_refresh(0);
             ncurses_wrefresh($r_status);
         }
         //
         // Get data for current row
         //
         $va_row = array_merge($o_reader->getRow(), $va_environment);
         //
         // Apply rules
         //
         foreach ($va_mapping_rules as $va_rule) {
             if (!isset($va_rule['trigger']) || !$va_rule['trigger']) {
                 continue;
             }
             if (!isset($va_rule['actions']) || !is_array($va_rule['actions']) || !sizeof($va_rule['actions'])) {
                 continue;
             }
             $vm_ret = ExpressionParser::evaluate($va_rule['trigger'], $va_row);
             if (!ExpressionParser::hadError() && (bool) $vm_ret) {
                 foreach ($va_rule['actions'] as $va_action) {
                     if (!is_array($va_action) && strtolower($va_action) == 'skip') {
                         $va_action = array('action' => 'skip');
                     }
                     switch ($vs_action_code = strtolower($va_action['action'])) {
                         case 'set':
                             $va_row[$va_action['target']] = $va_action['value'];
                             // TODO: transform value using mapping rules?
                             break;
                         case 'skip':
                         default:
                             if ($vs_action_code != 'skip') {
                                 $o_log->logInfo(_t('Row was skipped using rule "%1" with default action because an invalid action ("%2") was specified', $va_rule['trigger'], $vs_action_code));
                             } else {
                                 $o_log->logDebug(_t('Row was skipped using rule "%1" with action "%2"', $va_rule['trigger'], $vs_action_code));
                             }
                             continue 4;
                             break;
                     }
                 }
             }
         }
         //
         // Perform mapping and insert
         //
         // Get minimal info for imported row (type_id, idno, label)
         // Get type
         if ($vn_type_id_mapping_item_id) {
             // Type is specified in row
             $vs_type = ca_data_importers::getValueFromSource($va_mapping_items[$vn_type_id_mapping_item_id], $o_reader, array('environment' => $va_environment));
         } else {
             // Type is constant for all rows
             $vs_type = $vs_type_mapping_setting;
         }
         // Get idno
         $vs_idno = null;
         if ($vn_idno_mapping_item_id) {
             // idno is specified in row
             $vs_idno = ca_data_importers::getValueFromSource($va_mapping_items[$vn_idno_mapping_item_id], $o_reader, array('environment' => $va_environment));
             if (isset($va_mapping_items[$vn_idno_mapping_item_id]['settings']['default']) && strlen($va_mapping_items[$vn_idno_mapping_item_id]['settings']['default']) && !strlen($vs_idno)) {
                 $vs_idno = $va_mapping_items[$vn_idno_mapping_item_id]['settings']['default'];
             }
             if (!is_array($vs_idno) && $vs_idno[0] == '^' && preg_match("!^\\^[^ ]+\$!", $vs_idno)) {
                 // Parse placeholder when it's at the beginning of the value
                 if (!is_null($vm_parsed_val = BaseRefinery::parsePlaceholder($vs_idno, $va_row, $va_item, null, array('reader' => $o_reader, 'returnAsString' => true)))) {
                     $vs_idno = $vm_parsed_val;
                 }
             }
             // Apply prefix/suffix *AFTER* setting default
             if ($vs_idno && isset($va_mapping_items[$vn_idno_mapping_item_id]['settings']['prefix']) && strlen($va_mapping_items[$vn_idno_mapping_item_id]['settings']['prefix'])) {
                 $vs_idno = $va_mapping_items[$vn_idno_mapping_item_id]['settings']['prefix'] . $vs_idno;
             }
             if ($vs_idno && isset($va_mapping_items[$vn_idno_mapping_item_id]['settings']['suffix']) && strlen($va_mapping_items[$vn_idno_mapping_item_id]['settings']['suffix'])) {
                 $vs_idno .= $va_mapping_items[$vn_idno_mapping_item_id]['settings']['suffix'];
             }
             if (isset($va_mapping_items[$vn_idno_mapping_item_id]['settings']['formatWithTemplate']) && strlen($va_mapping_items[$vn_idno_mapping_item_id]['settings']['formatWithTemplate'])) {
                 $vs_idno = caProcessTemplate($va_mapping_items[$vn_idno_mapping_item_id]['settings']['formatWithTemplate'], $va_row);
             }
         } else {
             $vs_idno = "%";
         }
         $vb_idno_is_template = (bool) preg_match('![%]+!', $vs_idno);
         // get preferred labels
         $va_pref_label_values = array();
         foreach ($va_preferred_label_mapping_ids as $vn_preferred_label_mapping_id => $vs_preferred_label_mapping_fld) {
             $vs_label_val = ca_data_importers::getValueFromSource($va_mapping_items[$vn_preferred_label_mapping_id], $o_reader, array('environment' => $va_environment));
             // If a template is specified format the label value with it so merge-on-preferred_label doesn't fail
             if (isset($va_mapping_items[$vn_preferred_label_mapping_id]['settings']['formatWithTemplate']) && strlen($va_mapping_items[$vn_preferred_label_mapping_id]['settings']['formatWithTemplate'])) {
                 $vs_label_val = caProcessTemplate($va_mapping_items[$vn_preferred_label_mapping_id]['settings']['formatWithTemplate'], $va_row);
             }
             $va_pref_label_values[$vs_preferred_label_mapping_fld] = $vs_label_val;
         }
         $vs_display_label = isset($va_pref_label_values[$vs_label_display_fld]) ? $va_pref_label_values[$vs_label_display_fld] : $vs_idno;
         //
         // Look for existing record?
         //
         if (is_array($pa_force_import_for_primary_keys) && sizeof($pa_force_import_for_primary_keys) > 0) {
             $vn_id = array_shift($pa_force_import_for_primary_keys);
             if (!$t_subject->load($vn_id)) {
                 $o_log->logInfo(_t('[%1] Skipped import because of forced primary key \'%1\' does not exist', $vn_id));
                 ca_data_importers::$s_num_records_skipped++;
                 continue;
                 // skip because primary key does not exist
             }
         } elseif ($vs_existing_record_policy != 'none') {
             switch ($vs_existing_record_policy) {
                 case 'skip_on_idno':
                     if (!$vb_idno_is_template) {
                         $va_ids = call_user_func_array($t_subject->tableName() . "::find", array(array('type_id' => $vs_type, $t_subject->getProperty('ID_NUMBERING_ID_FIELD') => $vs_idno, 'deleted' => 0), array('returnAs' => 'ids')));
                         if (is_array($va_ids) && sizeof($va_ids) > 0) {
                             $o_log->logInfo(_t('[%1] Skipped import because of existing record matched on identifier by policy %2', $vs_idno, $vs_existing_record_policy));
                             ca_data_importers::$s_num_records_skipped++;
                             continue 2;
                             // skip because idno matched
                         }
                     }
                     break;
                 case 'skip_on_preferred_labels':
                     $va_ids = call_user_func_array($t_subject->tableName() . "::find", array(array('type_id' => $vs_type, 'preferred_labels' => $va_pref_label_values, 'deleted' => 0), array('returnAs' => 'ids')));
                     if (is_array($va_ids) && sizeof($va_ids) > 0) {
                         $o_log->logInfo(_t('[%1] Skipped import because of existing record matched on label by policy %2', $vs_idno, $vs_existing_record_policy));
                         ca_data_importers::$s_num_records_skipped++;
                         continue 2;
                         // skip because label matched
                     }
                     break;
                 case 'merge_on_idno_and_preferred_labels':
                 case 'merge_on_idno':
                 case 'merge_on_idno_and_preferred_labels_with_replace':
                 case 'merge_on_idno_with_replace':
                     if (!$vb_idno_is_template) {
                         $va_ids = call_user_func_array($t_subject->tableName() . "::find", array(array('type_id' => $vs_type, $t_subject->getProperty('ID_NUMBERING_ID_FIELD') => $vs_idno, 'deleted' => 0), array('returnAs' => 'ids')));
                         if (is_array($va_ids) && sizeof($va_ids) > 0) {
                             $t_subject->load($va_ids[0]);
                             $o_log->logInfo(_t('[%1] Merged with existing record matched on identifer by policy %2', $vs_idno, $vs_existing_record_policy));
                             break;
                         }
                     }
                     if (in_array($vs_existing_record_policy, array('merge_on_idno', 'merge_on_idno_with_replace'))) {
                         break;
                     }
                     // fall through if merge_on_idno_and_preferred_labels
                 // fall through if merge_on_idno_and_preferred_labels
                 case 'merge_on_preferred_labels':
                 case 'merge_on_preferred_labels_with_replace':
                     $va_ids = call_user_func_array($t_subject->tableName() . "::find", array(array('type_id' => $vs_type, 'preferred_labels' => $va_pref_label_values, 'deleted' => 0), array('returnAs' => 'ids')));
                     if (is_array($va_ids) && sizeof($va_ids) > 0) {
                         $t_subject->load($va_ids[0]);
                         $o_log->logInfo(_t('[%1] Merged with existing record matched on label by policy %2', $vs_idno, $vs_existing_record_policy));
                     }
                     break;
                 case 'overwrite_on_idno_and_preferred_labels':
                 case 'overwrite_on_idno':
                     if (!$vb_idno_is_template && $vs_idno) {
                         $va_ids = call_user_func_array($t_subject->tableName() . "::find", array(array('type_id' => $vs_type, $t_subject->getProperty('ID_NUMBERING_ID_FIELD') => $vs_idno, 'deleted' => 0), array('returnAs' => 'ids')));
                         if (is_array($va_ids) && sizeof($va_ids) > 0) {
                             $t_subject->load($va_ids[0]);
                             $t_subject->setMode(ACCESS_WRITE);
                             $t_subject->delete(true, array('hard' => true));
                             if ($t_subject->numErrors()) {
                                 ca_data_importers::logImportError(_t('[%1] Could not delete existing record matched on identifier by policy %2', $vs_idno, $vs_existing_record_policy));
                                 // Don't stop?
                             } else {
                                 $o_log->logInfo(_t('[%1] Overwrote existing record matched on identifier by policy %2', $vs_idno, $vs_existing_record_policy));
                                 $t_subject->clear();
                                 break;
                             }
                         }
                     }
                     if ($vs_existing_record_policy == 'overwrite_on_idno') {
                         break;
                     }
                     // fall through if overwrite_on_idno_and_preferred_labels
                 // fall through if overwrite_on_idno_and_preferred_labels
                 case 'overwrite_on_preferred_labels':
                     $va_ids = call_user_func_array($t_subject->tableName() . "::find", array(array('type_id' => $vs_type, 'preferred_labels' => $va_pref_label_values, 'deleted' => 0), array('returnAs' => 'ids')));
                     if (is_array($va_ids) && sizeof($va_ids) > 0) {
                         $t_subject->load($va_ids[0]);
                         $t_subject->setMode(ACCESS_WRITE);
                         $t_subject->delete(true, array('hard' => true));
                         if ($t_subject->numErrors()) {
                             ca_data_importers::logImportError(_t('[%1] Could not delete existing record matched on label by policy %2', $vs_idno, $vs_existing_record_policy));
                             // Don't stop?
                         } else {
                             $o_log->logInfo(_t('[%1] Overwrote existing record matched on label by policy %2', $vs_idno, $vs_existing_record_policy));
                             break;
                         }
                         $t_subject->clear();
                     }
                     break;
             }
         }
         $o_progress->next(_t("Importing %1", $vs_idno), array('window' => $r_progress));
         if ($po_request && isset($pa_options['progressCallback']) && ($ps_callback = $pa_options['progressCallback'])) {
             $ps_callback($po_request, $pn_file_number, $pn_number_of_files, $ps_source, ca_data_importers::$s_num_records_processed, $vn_num_items, _t("[%3/%4] Processing %1 (%2)", caTruncateStringWithEllipsis($vs_display_label, 50), $vs_idno, ca_data_importers::$s_num_records_processed, $vn_num_items), time() - $vn_start_time, memory_get_usage(true), ca_data_importers::$s_num_records_processed, ca_data_importers::$s_num_import_errors);
         }
         $vb_output_subject_preferred_label = false;
         $va_content_tree = array();
         foreach ($va_items_by_group as $vn_group_id => $va_items) {
             $va_group = $va_mapping_groups[$vn_group_id];
             $vs_group_destination = $va_group['destination'];
             $va_group_tmp = explode(".", $vs_group_destination);
             if (sizeof($va_items) < 2 && sizeof($va_group_tmp) > 2) {
                 array_pop($va_group_tmp);
             }
             $vs_target_table = $va_group_tmp[0];
             if (!($t_target = $o_dm->getInstanceByTableName($vs_target_table, true))) {
                 // Invalid target table
                 $o_log->logWarn(_t('[%1] Skipped group %2 because target %3 is invalid', $vs_idno, $vn_group_id, $vs_target_table));
                 continue;
             }
             if ($o_trans) {
                 $t_target->setTransaction($o_trans);
             }
             $va_group_buf = array();
             foreach ($va_items as $vn_item_id => $va_item) {
                 if ($vb_use_as_single_value = caGetOption('useAsSingleValue', $va_item['settings'], false)) {
                     // Force repeating values to be imported as a single value
                     $va_vals = array(ca_data_importers::getValueFromSource($va_item, $o_reader, array('delimiter' => caGetOption('delimiter', $va_item['settings'], ''), 'returnAsArray' => false)));
                 } else {
                     $va_vals = ca_data_importers::getValueFromSource($va_item, $o_reader, array('returnAsArray' => true, 'environment' => $va_environment));
                 }
                 if (!sizeof($va_vals)) {
                     $va_vals = array(0 => null);
                 }
                 // consider missing values equivalent to blanks
                 // Do value conversions
                 foreach ($va_vals as $vn_i => $vm_val) {
                     if (isset($va_item['settings']['default']) && strlen($va_item['settings']['default']) && !strlen($vm_val)) {
                         $vm_val = $va_item['settings']['default'];
                     }
                     // Apply prefix/suffix *AFTER* setting default
                     if ($vm_val && isset($va_item['settings']['prefix']) && strlen($va_item['settings']['prefix'])) {
                         $vm_val = $va_item['settings']['prefix'] . $vm_val;
                     }
                     if ($vm_val && isset($va_item['settings']['suffix']) && strlen($va_item['settings']['suffix'])) {
                         $vm_val .= $va_item['settings']['suffix'];
                     }
                     if (!is_array($vm_val) && $vm_val[0] == '^' && preg_match("!^\\^[^ ]+\$!", $vm_val)) {
                         // Parse placeholder
                         if (!is_null($vm_parsed_val = BaseRefinery::parsePlaceholder($vm_val, $va_row, $va_item, $vn_i, array('reader' => $o_reader, 'returnAsString' => true)))) {
                             $vm_val = $vm_parsed_val;
                         }
                     }
                     if (isset($va_item['settings']['formatWithTemplate']) && strlen($va_item['settings']['formatWithTemplate'])) {
                         $vm_val = caProcessTemplate($va_item['settings']['formatWithTemplate'], array_replace($va_row, array((string) $va_item['source'] => ca_data_importers::replaceValue($vm_val, $va_item))), array('getFrom' => $o_reader));
                     }
                     if (isset($va_item['settings']['applyRegularExpressions']) && is_array($va_item['settings']['applyRegularExpressions'])) {
                         if (is_array($va_item['settings']['applyRegularExpressions'])) {
                             foreach ($va_item['settings']['applyRegularExpressions'] as $vn_regex_index => $va_regex) {
                                 if (!strlen($va_regex['match'])) {
                                     continue;
                                 }
                                 $vm_val = preg_replace("!" . str_replace("!", "\\!", $va_regex['match']) . "!" . (isset($va_regex['caseSensitive']) && (bool) $va_regex['caseSensitive'] ? '' : 'i'), $va_regex['replaceWith'], $vm_val);
                             }
                         }
                     }
                     $va_vals[$vn_i] = $vm_val;
                     if ($o_reader->valuesCanRepeat()) {
                         $va_row[$va_item['source']][$vn_i] = $va_row[mb_strtolower($va_item['source'])][$vn_i] = $vm_val;
                     } else {
                         $va_row[$va_item['source']] = $va_row[mb_strtolower($va_item['source'])] = $vm_val;
                     }
                 }
                 // Process each value
                 $vn_c = -1;
                 foreach ($va_vals as $vn_i => $vm_val) {
                     $vn_c++;
                     if (isset($va_item['settings']['convertNewlinesToHTML']) && (bool) $va_item['settings']['convertNewlinesToHTML'] && is_string($vm_val)) {
                         $vm_val = nl2br($vm_val);
                     }
                     // Get location in content tree for addition of new content
                     $va_item_dest = explode(".", $va_item['destination']);
                     $vs_item_terminal = $va_item_dest[sizeof($va_item_dest) - 1];
                     if (isset($va_item['settings']['restrictToTypes']) && is_array($va_item['settings']['restrictToTypes']) && !in_array($vs_type, $va_item['settings']['restrictToTypes'])) {
                         $o_log->logInfo(_t('[%1] Skipped row %2 because of type restriction', $vs_idno, $vn_row));
                         continue 4;
                     }
                     if (isset($va_item['settings']['skipRowIfEmpty']) && (bool) $va_item['settings']['skipRowIfEmpty'] && !strlen($vm_val)) {
                         $o_log->logInfo(_t('[%1] Skipped row %2 because value for %3 in group %4 is empty', $vs_idno, $vn_row, $vs_item_terminal, $vn_group_id));
                         continue 4;
                     }
                     if (isset($va_item['settings']['skipRowIfValue']) && is_array($va_item['settings']['skipRowIfValue']) && strlen($vm_val) && in_array($vm_val, $va_item['settings']['skipRowIfValue'])) {
                         $o_log->logInfo(_t('[%1] Skipped row %2 because value for %3 in group %4 matches value %5', $vs_idno, $vn_row, $vs_item_terminal, $vn_group_id));
                         continue 4;
                     }
                     if (isset($va_item['settings']['skipRowIfNotValue']) && is_array($va_item['settings']['skipRowIfNotValue']) && strlen($vm_val) && !in_array($vm_val, $va_item['settings']['skipRowIfNotValue'])) {
                         $o_log->logInfo(_t('[%1] Skipped row %2 because value for %3 in group %4 is not in list of values', $vs_idno, $vn_row, $vs_item_terminal, $vn_group_id, $vm_val));
                         continue 4;
                     }
                     if (isset($va_item['settings']['skipGroupIfEmpty']) && (bool) $va_item['settings']['skipGroupIfEmpty'] && !strlen($vm_val)) {
                         $o_log->logInfo(_t('[%1] Skipped group %2 because value for %3 is empty', $vs_idno, $vn_group_id, $vs_item_terminal));
                         continue 3;
                     }
                     if (isset($va_item['settings']['skipGroupIfExpression']) && strlen(trim($va_item['settings']['skipGroupIfExpression']))) {
                         if ($vm_ret = ExpressionParser::evaluate($va_item['settings']['skipGroupIfExpression'], $va_row)) {
                             $o_log->logInfo(_t('[%1] Skipped group %2 because expression %3 is true', $vs_idno, $vn_group_id, $va_item['settings']['skipGroupIfExpression']));
                             continue 3;
                         }
                     }
                     if (isset($va_item['settings']['skipGroupIfValue']) && is_array($va_item['settings']['skipGroupIfValue']) && strlen($vm_val) && in_array($vm_val, $va_item['settings']['skipGroupIfValue'])) {
                         $o_log->logInfo(_t('[%1] Skipped group %2 because value for %3 matches value %4', $vs_idno, $vn_group_id, $vs_item_terminal, $vm_val));
                         continue 3;
                     }
                     if (isset($va_item['settings']['skipGroupIfNotValue']) && is_array($va_item['settings']['skipGroupIfNotValue']) && strlen($vm_val) && !in_array($vm_val, $va_item['settings']['skipGroupIfNotValue'])) {
                         $o_log->logInfo(_t('[%1] Skipped group %2 because value for %3 matches is not in list of values', $vs_idno, $vn_group_id, $vs_item_terminal));
                         continue 3;
                     }
                     if (isset($va_item['settings']['skipIfExpression']) && strlen(trim($va_item['settings']['skipIfExpression']))) {
                         if ($vm_ret = ExpressionParser::evaluate($va_item['settings']['skipIfExpression'], $va_row)) {
                             $o_log->logInfo(_t('[%1] Skipped mapping because expression %2 is true', $vs_idno, $va_item['settings']['skipIfExpression']));
                             continue 2;
                         }
                     }
                     if (isset($va_item['settings']['skipIfEmpty']) && (bool) $va_item['settings']['skipIfEmpty'] && !strlen($vm_val)) {
                         $o_log->logInfo(_t('[%1] Skipped mapping because value for %2 is empty', $vs_idno, $vs_item_terminal));
                         continue 2;
                     }
                     if ($vn_type_id_mapping_item_id && $vn_item_id == $vn_type_id_mapping_item_id) {
                         continue;
                     }
                     if ($vn_idno_mapping_item_id && $vn_item_id == $vn_idno_mapping_item_id) {
                         continue;
                     }
                     if (is_null($vm_val)) {
                         continue;
                     }
                     // Get mapping error policy
                     $vb_item_error_policy_is_default = false;
                     if (!isset($va_item['settings']['errorPolicy']) || !in_array($vs_item_error_policy = $va_item['settings']['errorPolicy'], array('ignore', 'stop'))) {
                         $vs_item_error_policy = 'ignore';
                         $vb_item_error_policy_is_default = true;
                     }
                     //
                     if (isset($va_item['settings']['relationshipType']) && strlen($vs_rel_type = $va_item['settings']['relationshipType']) && $vs_target_table != $vs_subject_table) {
                         $va_group_buf[$vn_c]['_relationship_type'] = $vs_rel_type;
                     }
                     // Is it a constant value?
                     if (preg_match("!^_CONSTANT_:[\\d]+:(.*)!", $va_item['source'], $va_matches)) {
                         $va_group_buf[$vn_c][$vs_item_terminal] = $va_matches[1];
                         // Set it and go onto the next item
                         if ($vs_target_table == $vs_subject_table_name && ($vs_k = array_search($vn_item_id, $va_mandatory_field_mapping_ids)) !== false) {
                             $va_mandatory_field_values[$vs_k] = $vm_val;
                         }
                         continue;
                     }
                     // Perform refinery call (if required) per value
                     if (isset($va_item['settings']['refineries']) && is_array($va_item['settings']['refineries'])) {
                         foreach ($va_item['settings']['refineries'] as $vs_refinery) {
                             if (!$vs_refinery) {
                                 continue;
                             }
                             if ($o_refinery = RefineryManager::getRefineryInstance($vs_refinery)) {
                                 $va_refined_values = $o_refinery->refine($va_content_tree, $va_group, $va_item, $va_row, array('mapping' => $t_mapping, 'source' => $ps_source, 'subject' => $t_subject, 'locale_id' => $vn_locale_id, 'log' => $o_log, 'transaction' => $o_trans, 'importEvent' => $o_event, 'importEventSource' => $vn_row, 'reader' => $o_reader, 'valueIndex' => $vn_i));
                                 if (!$va_refined_values || is_array($va_refined_values) && !sizeof($va_refined_values)) {
                                     continue 2;
                                 }
                                 if ($o_refinery->returnsMultipleValues()) {
                                     foreach ($va_refined_values as $va_refined_value) {
                                         $va_refined_value['_errorPolicy'] = $vs_item_error_policy;
                                         if (!is_array($va_group_buf[$vn_c])) {
                                             $va_group_buf[$vn_c] = array();
                                         }
                                         $va_group_buf[$vn_c] = array_merge($va_group_buf[$vn_c], $va_refined_value);
                                         $vn_c++;
                                     }
                                 } else {
                                     $va_group_buf[$vn_c]['_errorPolicy'] = $vs_item_error_policy;
                                     $va_group_buf[$vn_c][$vs_item_terminal] = $va_refined_values;
                                     $vn_c++;
                                 }
                                 if ($vs_target_table == $vs_subject_table_name && ($vs_k = array_search($vn_item_id, $va_mandatory_field_mapping_ids)) !== false) {
                                     $va_mandatory_field_values[$vs_k] = $vm_val;
                                 }
                                 continue 2;
                             } else {
                                 ca_data_importers::logImportError(_t('[%1] Invalid refinery %2 specified', $vs_idno, $vs_refinery));
                             }
                         }
                     }
                     if ($vs_target_table == $vs_subject_table_name && ($vs_k = array_search($vn_item_id, $va_mandatory_field_mapping_ids)) !== false) {
                         $va_mandatory_field_values[$vs_k] = $vm_val;
                     }
                     $vn_max_length = !is_array($vm_val) && isset($va_item['settings']['maxLength']) && (int) $va_item['settings']['maxLength'] ? (int) $va_item['settings']['maxLength'] : null;
                     if (isset($va_item['settings']['delimiter']) && $va_item['settings']['delimiter']) {
                         if (!is_array($va_item['settings']['delimiter'])) {
                             $va_item['settings']['delimiter'] = array($va_item['settings']['delimiter']);
                         }
                         if (sizeof($va_item['settings']['delimiter'])) {
                             foreach ($va_item['settings']['delimiter'] as $vn_index => $vs_delim) {
                                 $va_item['settings']['delimiter'][$vn_index] = preg_quote($vs_delim, "!");
                             }
                             $va_val_list = preg_split("!(" . join("|", $va_item['settings']['delimiter']) . ")!", $vm_val);
                             // Add delimited values
                             foreach ($va_val_list as $vs_list_val) {
                                 $vs_list_val = trim(ca_data_importers::replaceValue($vs_list_val, $va_item));
                                 if ($vn_max_length && mb_strlen($vs_list_val) > $vn_max_length) {
                                     $vs_list_val = mb_substr($vs_list_val, 0, $vn_max_length);
                                 }
                                 $va_group_buf[$vn_c] = array($vs_item_terminal => $vs_list_val, '_errorPolicy' => $vs_item_error_policy);
                                 $vn_c++;
                             }
                             $vn_row++;
                             continue;
                             // Don't add "regular" value below
                         }
                     }
                     if ($vn_max_length && mb_strlen($vm_val) > $vn_max_length) {
                         $vm_val = mb_substr($vm_val, 0, $vn_max_length);
                     }
                     switch ($vs_item_terminal) {
                         case 'preferred_labels':
                         case 'nonpreferred_labels':
                             if ($t_instance = $o_dm->getInstanceByTableName($vs_target_table, true)) {
                                 $va_group_buf[$vn_c][$t_instance->getLabelDisplayField()] = $vm_val;
                             }
                             if ($o_trans) {
                                 $t_instance->setTransaction($o_trans);
                             }
                             if (!$vb_item_error_policy_is_default || !isset($va_group_buf[$vn_c]['_errorPolicy'])) {
                                 if (is_array($va_group_buf[$vn_c])) {
                                     $va_group_buf[$vn_c]['_errorPolicy'] = $vs_item_error_policy;
                                 }
                             }
                             if ($vs_item_terminal == 'preferred_labels') {
                                 $vs_preferred_label_for_log = $vm_val;
                             }
                             break;
                         default:
                             $va_group_buf[$vn_c][$vs_item_terminal] = $vm_val;
                             if (!$vb_item_error_policy_is_default || !isset($va_group_buf[$vn_c]['_errorPolicy'])) {
                                 if (is_array($va_group_buf[$vn_c])) {
                                     $va_group_buf[$vn_c]['_errorPolicy'] = $vs_item_error_policy;
                                 }
                             }
                             break;
                     }
                 }
                 // end foreach($va_vals as $vm_val)
             }
             foreach ($va_group_buf as $vn_group_index => $va_group_data) {
                 $va_ptr =& $va_content_tree;
                 foreach ($va_group_tmp as $vs_tmp) {
                     if (!is_array($va_ptr[$vs_tmp])) {
                         $va_ptr[$vs_tmp] = array();
                     }
                     $va_ptr =& $va_ptr[$vs_tmp];
                     if ($vs_tmp == $vs_target_table) {
                         // add numeric index after table to ensure repeat values don't overwrite each other
                         $va_parent =& $va_ptr;
                         $va_ptr[] = array();
                         $va_ptr =& $va_ptr[sizeof($va_ptr) - 1];
                     }
                 }
                 $va_ptr = $va_group_data;
             }
         }
         //
         // Process out self-relationships
         //
         if (is_array($va_content_tree[$vs_subject_table])) {
             $va_self_related_content = array();
             foreach ($va_content_tree[$vs_subject_table] as $vn_i => $va_element_data) {
                 if (isset($va_element_data['_relationship_type'])) {
                     $va_self_related_content[] = $va_element_data;
                     unset($va_content_tree[$vs_subject_table][$vn_i]);
                 }
             }
             if (sizeof($va_self_related_content) > 0) {
                 $va_content_tree["related.{$vs_subject_table}"] = $va_self_related_content;
             }
         }
         $vn_row++;
         $o_log->logDebug(_t('Finished building content tree for %1 at %2 seconds', $vs_idno, $t->getTime(4)));
         $o_log->logDebug(_t("Content tree is\n%1", print_R($va_content_tree, true)));
         //
         // Process data in subject record
         //
         //print_r($va_content_tree);
         //die("END\n\n");
         //continue;
         $opa_app_plugin_manager->hookDataImportContentTree(array('mapping' => $t_mapping, 'content_tree' => &$va_content_tree, 'idno' => &$vs_idno, 'transaction' => &$o_trans, 'log' => &$o_log, 'reader' => $o_reader, 'environment' => $va_environment, 'importEvent' => $o_event, 'importEventSource' => $vn_row));
         //print_r($va_content_tree);
         //die("done\n");
         if (!sizeof($va_content_tree) && !str_replace("%", "", $vs_idno)) {
             continue;
         }
         if (!$t_subject->getPrimaryKey()) {
             $o_event->beginItem($vn_row, $t_subject->tableNum(), 'I');
             $t_subject->setMode(ACCESS_WRITE);
             $t_subject->set($vs_type_id_fld, $vs_type);
             if ($vb_idno_is_template) {
                 $t_subject->setIdnoWithTemplate($vs_idno);
             } else {
                 $t_subject->set($vs_idno_fld, $vs_idno, array('assumeIdnoForRepresentationID' => true, 'assumeIdnoStubForLotID' => true));
                 // assumeIdnoStubForLotID forces ca_objects.lot_id values to always be considered as a potential idno_stub first, before use as a ca_objects.lot_id
             }
             // Look for parent_id in the content tree
             $vs_parent_id_fld = $t_subject->getProperty('HIERARCHY_PARENT_ID_FLD');
             foreach ($va_content_tree as $vs_table_name => $va_content) {
                 if ($vs_table_name == $vs_subject_table) {
                     foreach ($va_content as $va_element_data) {
                         foreach ($va_element_data as $vs_element => $va_element_content) {
                             switch ($vs_element) {
                                 case $vs_parent_id_fld:
                                     if ($va_element_content[$vs_parent_id_fld]) {
                                         $t_subject->set($vs_parent_id_fld, $va_element_content[$vs_parent_id_fld], array('treatParentIDAsIdno' => true));
                                     }
                                     break;
                             }
                         }
                     }
                 }
             }
             foreach ($va_mandatory_field_mapping_ids as $vs_mandatory_field => $vn_mandatory_mapping_item_id) {
                 $t_subject->set($vs_mandatory_field, $va_mandatory_field_values[$vs_mandatory_field], array('assumeIdnoStubForLotID' => true));
             }
             $t_subject->insert();
             if ($vs_error = DataMigrationUtils::postError($t_subject, _t("Could not insert new record"), array('dontOutputLevel' => true, 'dontPrint' => true))) {
                 ca_data_importers::logImportError($vs_error, $va_log_import_error_opts);
                 if ($vs_import_error_policy == 'stop') {
                     $o_log->logAlert(_t('Import stopped due to import error policy'));
                     if ($vb_use_ncurses) {
                         ncurses_end();
                     }
                     $o_event->endItem($t_subject->getPrimaryKey(), __CA_DATA_IMPORT_ITEM_FAILURE__, _t('Failed to import %1', $vs_idno));
                     if ($o_trans) {
                         $o_trans->rollback();
                     }
                     return false;
                 }
                 continue;
             }
             $o_log->logDebug(_t('Created idno %1 at %2 seconds', $vs_idno, $t->getTime(4)));
         } else {
             $o_event->beginItem($vn_row, $t_subject->tableNum(), 'U');
             // update
             $t_subject->setMode(ACCESS_WRITE);
             if ($vb_idno_is_template) {
                 $t_subject->setIdnoWithTemplate($vs_idno);
             } else {
                 $t_subject->set($vs_idno_fld, $vs_idno, array('assumeIdnoStubForLotID' => true));
                 // assumeIdnoStubForLotID forces ca_objects.lot_id values to always be considered as a potential idno_stub first, before use as a ca_objects.lot_di
             }
             $t_subject->update();
             if ($vs_error = DataMigrationUtils::postError($t_subject, _t("Could not update matched record"), array('dontOutputLevel' => true, 'dontPrint' => true))) {
                 ca_data_importers::logImportError($vs_error, $va_log_import_error_opts);
                 if ($vs_import_error_policy == 'stop') {
                     $o_log->logAlert(_t('Import stopped due to import error policy'));
                     if ($vb_use_ncurses) {
                         ncurses_end();
                     }
                     $o_event->endItem($t_subject->getPrimaryKey(), __CA_DATA_IMPORT_ITEM_FAILURE__, _t('Failed to import %1', $vs_idno));
                     if ($o_trans) {
                         $o_trans->rollback();
                     }
                     return false;
                 }
                 continue;
             }
             $t_subject->clearErrors();
             if (sizeof($va_preferred_label_mapping_ids) && $t_subject->getPreferredLabelCount() > 0) {
                 $t_subject->removeAllLabels(__CA_LABEL_TYPE_PREFERRED__);
                 if ($vs_error = DataMigrationUtils::postError($t_subject, _t("Could not update remove preferred labels from matched record"), array('dontOutputLevel' => true, 'dontPrint' => true))) {
                     ca_data_importers::logImportError($vs_error, $va_log_import_error_opts);
                     if ($vs_import_error_policy == 'stop') {
                         $o_log->logAlert(_t('Import stopped due to import error policy'));
                         if ($vb_use_ncurses) {
                             ncurses_end();
                         }
                         if ($o_trans) {
                             $o_trans->rollback();
                         }
                         $o_event->endItem($t_subject->getPrimaryKey(), __CA_DATA_IMPORT_ITEM_FAILURE__, _t('Failed to import %1', $vs_idno));
                         return false;
                     }
                 }
             }
             $o_log->logDebug(_t('Updated idno %1 at %2 seconds', $vs_idno, $t->getTime(4)));
         }
         if ($vs_idno_fld && ($o_idno = $t_subject->getIDNoPlugInInstance())) {
             $va_values = $o_idno->htmlFormValuesAsArray($vs_idno_fld, $t_subject->get($vs_idno_fld));
             if (!is_array($va_values)) {
                 $va_values = array($va_values);
             }
             if (($vs_proc_idno = join($o_idno->getSeparator(), $va_values)) && $vs_proc_idno != $vs_idno) {
                 $t_subject->set($vs_idno_fld, $vs_proc_idno);
                 $t_subject->update();
                 if ($vs_error = DataMigrationUtils::postError($t_subject, _t("Could update idno"), array('dontOutputLevel' => true, 'dontPrint' => true))) {
                     ca_data_importers::logImportError($vs_error, $va_log_import_error_opts);
                     if ($vs_import_error_policy == 'stop') {
                         $o_log->logAlert(_t('Import stopped due to import error policy'));
                         if ($vb_use_ncurses) {
                             ncurses_end();
                         }
                         $o_event->endItem($t_subject->getPrimaryKey(), __CA_DATA_IMPORT_ITEM_FAILURE__, _t('Failed to import %1', $vs_idno));
                         if ($o_trans) {
                             $o_trans->rollback();
                         }
                         return false;
                     }
                     continue;
                 }
             }
         }
         $va_elements_set_for_this_record = array();
         foreach ($va_content_tree as $vs_table_name => $va_content) {
             if ($vs_table_name == $vs_subject_table) {
                 foreach ($va_content as $vn_i => $va_element_data) {
                     foreach ($va_element_data as $vs_element => $va_element_content) {
                         if (is_array($va_element_content)) {
                             $vs_item_error_policy = $va_element_content['_errorPolicy'];
                             unset($va_element_content['_errorPolicy']);
                         } else {
                             $vs_item_error_policy = null;
                         }
                         $t_subject->clearErrors();
                         $t_subject->setMode(ACCESS_WRITE);
                         switch ($vs_element) {
                             case 'preferred_labels':
                                 $t_subject->addLabel($va_element_content, $vn_locale_id, isset($va_element_content['type_id']) ? $va_element_content['type_id'] : null, true);
                                 if ($t_subject->numErrors() == 0) {
                                     $vb_output_subject_preferred_label = true;
                                 }
                                 if ($vs_error = DataMigrationUtils::postError($t_subject, _t("[%1] Could not add preferred label to %2. Record was deleted because no preferred label could be applied: ", $vs_idno, $t_subject->tableName()), __CA_DATA_IMPORT_ERROR__, array('dontOutputLevel' => true, 'dontPrint' => true))) {
                                     ca_data_importers::logImportError($vs_error, $va_log_import_error_opts);
                                     $t_subject->delete(true, array('hard' => false));
                                     if ($vs_import_error_policy == 'stop') {
                                         $o_log->logAlert(_t('Import stopped due to import error policy %1', $vs_import_error_policy));
                                         if ($vb_use_ncurses) {
                                             ncurses_end();
                                         }
                                         $o_event->endItem($t_subject->getPrimaryKey(), __CA_DATA_IMPORT_ITEM_FAILURE__, _t('Failed to import %1', $vs_idno));
                                         if ($o_trans) {
                                             $o_trans->rollback();
                                         }
                                         return false;
                                     }
                                     if ($vs_item_error_policy == 'stop') {
                                         $o_log->logAlert(_t('Import stopped due to mapping error policy'));
                                         if ($vb_use_ncurses) {
                                             ncurses_end();
                                         }
                                         if ($o_trans) {
                                             $o_trans->rollback();
                                         }
                                         return false;
                                     }
                                     continue 5;
                                 }
                                 break;
                             case 'nonpreferred_labels':
                                 $t_subject->addLabel($va_element_content, $vn_locale_id, isset($va_element_content['type_id']) ? $va_element_content['type_id'] : null, false);
                                 if ($vs_error = DataMigrationUtils::postError($t_subject, _t("[%1] Could not add non-preferred label to %2:", $vs_idno, $t_subject->tableName()), __CA_DATA_IMPORT_ERROR__, array('dontOutputLevel' => true, 'dontPrint' => true))) {
                                     ca_data_importers::logImportError($vs_error, $va_log_import_error_opts);
                                     if ($vs_item_error_policy == 'stop') {
                                         $o_log->logAlert(_t('Import stopped due to mapping error policy'));
                                         if ($vb_use_ncurses) {
                                             ncurses_end();
                                         }
                                         $o_event->endItem($t_subject->getPrimaryKey(), __CA_DATA_IMPORT_ITEM_FAILURE__, _t('Failed to import %1', $vs_idno));
                                         if ($o_trans) {
                                             $o_trans->rollback();
                                         }
                                         return false;
                                     }
                                 }
                                 break;
                             default:
                                 if ($t_subject->hasField($vs_element)) {
                                     $t_subject->set($vs_element, $va_element_content[$vs_element], array('assumeIdnoStubForLotID' => true));
                                     $t_subject->update();
                                     break;
                                 }
                                 if ($vs_subject_table == 'ca_representation_annotations' && $vs_element == 'properties') {
                                     foreach ($va_element_content as $vs_prop => $vs_prop_val) {
                                         $t_subject->setPropertyValue($vs_prop, $vs_prop_val);
                                     }
                                     break;
                                 }
                                 if (is_array($va_element_content)) {
                                     $va_element_content['locale_id'] = $vn_locale_id;
                                 }
                                 if (!isset($va_elements_set_for_this_record[$vs_element]) && !$va_elements_set_for_this_record[$vs_element] && in_array($vs_existing_record_policy, array('merge_on_idno_with_replace', 'merge_on_preferred_labels_with_replace', 'merge_on_idno_and_preferred_labels_with_replace'))) {
                                     $t_subject->removeAttributes($vs_element, array('force' => true));
                                 }
                                 $va_elements_set_for_this_record[$vs_element] = true;
                                 $t_subject->addAttribute($va_element_content, $vs_element, null, array('showRepeatCountErrors' => true, 'alwaysTreatValueAsIdno' => true));
                                 if ($vs_error = DataMigrationUtils::postError($t_subject, _t("[%1] Failed to add value for %2; values were %3: ", $vs_idno, $vs_element, ca_data_importers::formatValuesForLog($va_element_content)), __CA_DATA_IMPORT_ERROR__, array('dontOutputLevel' => true, 'dontPrint' => true))) {
                                     ca_data_importers::logImportError($vs_error, $va_log_import_error_opts);
                                     if ($vs_item_error_policy == 'stop') {
                                         $o_log->logAlert(_t('Import stopped due to mapping error policy'));
                                         if ($vb_use_ncurses) {
                                             ncurses_end();
                                         }
                                         $o_event->endItem($t_subject->getPrimaryKey(), __CA_DATA_IMPORT_ITEM_FAILURE__, _t('Failed to import %1', $vs_idno));
                                         if ($o_trans) {
                                             $o_trans->rollback();
                                         }
                                         return false;
                                     }
                                 }
                                 $t_subject->update();
                                 if ($vs_error = DataMigrationUtils::postError($t_subject, _t("[%1] Invalid %2; values were %3: ", $vs_idno, $vs_element, ca_data_importers::formatValuesForLog($va_element_content)), __CA_DATA_IMPORT_ERROR__, array('dontOutputLevel' => true, 'dontPrint' => true))) {
                                     ca_data_importers::logImportError($vs_error, $va_log_import_error_opts);
                                     if ($vs_item_error_policy == 'stop') {
                                         $o_log->logAlert(_t('Import stopped due to mapping error policy'));
                                         if ($vb_use_ncurses) {
                                             ncurses_end();
                                         }
                                         $o_event->endItem($t_subject->getPrimaryKey(), __CA_DATA_IMPORT_ITEM_FAILURE__, _t('Failed to import %1', $vs_idno));
                                         if ($o_trans) {
                                             $o_trans->rollback();
                                         }
                                         return false;
                                     }
                                 }
                                 break;
                         }
                     }
                 }
             } else {
                 // related
                 $vs_table_name = preg_replace('!^related\\.!', '', $vs_table_name);
                 foreach ($va_content as $vn_i => $va_element_data) {
                     $va_match_on = caGetOption('_matchOn', $va_element_data, null);
                     $vb_dont_create = caGetOption('_dontCreate', $va_element_data, null);
                     $va_data_for_rel_table = $va_element_data;
                     $va_nonpreferred_labels = isset($va_data_for_rel_table['nonpreferred_labels']) ? $va_data_for_rel_table['nonpreferred_labels'] : null;
                     unset($va_data_for_rel_table['preferred_labels']);
                     unset($va_data_for_rel_table['_relationship_type']);
                     unset($va_data_for_rel_table['_type']);
                     unset($va_data_for_rel_table['_parent_id']);
                     unset($va_data_for_rel_table['_errorPolicy']);
                     unset($va_data_for_rel_table['_matchOn']);
                     $va_data_for_rel_table = array_merge($va_data_for_rel_table, ca_data_importers::_extractIntrinsicValues($va_data_for_rel_table, $vs_table_name));
                     $t_subject->clearErrors();
                     switch ($vs_table_name) {
                         case 'ca_objects':
                             if ($vn_rel_id = DataMigrationUtils::getObjectID($va_element_data['preferred_labels']['name'], $va_element_data['_parent_id'], $va_element_data['_type'], $vn_locale_id, $va_data_for_rel_table, array('dontCreate' => $vb_dont_create, 'matchOn' => $va_match_on, 'log' => $o_log, 'transaction' => $o_trans, 'importEvent' => $o_event, 'importEventSource' => $vn_row, 'nonPreferredLabels' => $va_nonpreferred_labels))) {
                                 if (!($vs_rel_type = $va_element_data['_relationship_type']) && !($vs_rel_type = $va_element_data['idno']['_relationship_type'])) {
                                     break;
                                 }
                                 $t_subject->addRelationship($vs_table_name, $vn_rel_id, trim($va_element_data['_relationship_type']), null, null, null, null, array('interstitialValues' => $va_element_data['_interstitial']));
                                 if ($vs_error = DataMigrationUtils::postError($t_subject, _t("[%1] Could not add related object with relationship %2:", $vs_idno, trim($va_element_data['_relationship_type'])), __CA_DATA_IMPORT_ERROR__, array('dontOutputLevel' => true, 'dontPrint' => true))) {
                                     ca_data_importers::logImportError($vs_error, $va_log_import_error_opts);
                                     if ($vs_item_error_policy == 'stop') {
                                         $o_log->logAlert(_t('Import stopped due to mapping error policy'));
                                         if ($vb_use_ncurses) {
                                             ncurses_end();
                                         }
                                         if ($o_trans) {
                                             $o_trans->rollback();
                                         }
                                         return false;
                                     }
                                 }
                             }
                             break;
                         case 'ca_object_lots':
                             $vs_idno_stub = null;
                             if (is_array($va_element_data['idno_stub'])) {
                                 $vs_idno_stub = isset($va_element_data['idno_stub']['idno_stub']) ? $va_element_data['idno_stub']['idno_stub'] : '';
                             } else {
                                 $vs_idno_stub = isset($va_element_data['idno_stub']) ? $va_element_data['idno_stub'] : '';
                             }
                             if ($vn_rel_id = DataMigrationUtils::getObjectLotID($vs_idno_stub, $va_element_data['preferred_labels']['name'], $va_element_data['_type'], $vn_locale_id, $va_data_for_rel_table, array('dontCreate' => $vb_dont_create, 'matchOn' => $va_match_on, 'log' => $o_log, 'transaction' => $o_trans, 'importEvent' => $o_event, 'importEventSource' => $vn_row, 'nonPreferredLabels' => $va_nonpreferred_labels))) {
                                 if (!($vs_rel_type = $va_element_data['_relationship_type']) && !($vs_rel_type = $va_element_data['idno_stub']['_relationship_type'])) {
                                     break;
                                 }
                                 $t_subject->addRelationship($vs_table_name, $vn_rel_id, trim($va_element_data['_relationship_type']), null, null, null, null, array('interstitialValues' => $va_element_data['_interstitial']));
                                 if ($vs_error = DataMigrationUtils::postError($t_subject, _t("[%1] Could not add related object lot with relationship %2:", $vs_idno, trim($va_element_data['_relationship_type'])), __CA_DATA_IMPORT_ERROR__, array('dontOutputLevel' => true, 'dontPrint' => true))) {
                                     ca_data_importers::logImportError($vs_error, $va_log_import_error_opts);
                                     if ($vs_item_error_policy == 'stop') {
                                         $o_log->logAlert(_t('Import stopped due to mapping error policy'));
                                         if ($vb_use_ncurses) {
                                             ncurses_end();
                                         }
                                         if ($o_trans) {
                                             $o_trans->rollback();
                                         }
                                         return false;
                                     }
                                 }
                             }
                             break;
                         case 'ca_entities':
                             if ($vn_rel_id = DataMigrationUtils::getEntityID($va_element_data['preferred_labels'], $va_element_data['_type'], $vn_locale_id, $va_data_for_rel_table, array('dontCreate' => $vb_dont_create, 'matchOn' => $va_match_on, 'log' => $o_log, 'transaction' => $o_trans, 'importEvent' => $o_event, 'importEventSource' => $vn_row, 'nonPreferredLabels' => $va_nonpreferred_labels))) {
                                 if (!($vs_rel_type = $va_element_data['_relationship_type']) && !($vs_rel_type = $va_element_data['idno']['_relationship_type'])) {
                                     break;
                                 }
                                 $t_subject->addRelationship($vs_table_name, $vn_rel_id, trim($va_element_data['_relationship_type']), null, null, null, null, array('interstitialValues' => $va_element_data['_interstitial']));
                                 if ($vs_error = DataMigrationUtils::postError($t_subject, _t("[%1] Could not add related entity with relationship %2:", $vs_idno, trim($va_element_data['_relationship_type'])), __CA_DATA_IMPORT_ERROR__, array('dontOutputLevel' => true, 'dontPrint' => true))) {
                                     ca_data_importers::logImportError($vs_error, $va_log_import_error_opts);
                                     if ($vs_item_error_policy == 'stop') {
                                         $o_log->logAlert(_t('Import stopped due to mapping error policy'));
                                         if ($vb_use_ncurses) {
                                             ncurses_end();
                                         }
                                         if ($o_trans) {
                                             $o_trans->rollback();
                                         }
                                         return false;
                                     }
                                 }
                             }
                             break;
                         case 'ca_places':
                             if ($vn_rel_id = DataMigrationUtils::getPlaceID($va_element_data['preferred_labels']['name'], $va_element_data['_parent_id'], $va_element_data['_type'], $vn_locale_id, $va_data_for_rel_table, array('dontCreate' => $vb_dont_create, 'matchOn' => $va_match_on, 'log' => $o_log, 'transaction' => $o_trans, 'importEvent' => $o_event, 'importEventSource' => $vn_row, 'nonPreferredLabels' => $va_nonpreferred_labels))) {
                                 if (!($vs_rel_type = $va_element_data['_relationship_type']) && !($vs_rel_type = $va_element_data['idno']['_relationship_type'])) {
                                     break;
                                 }
                                 $t_subject->addRelationship($vs_table_name, $vn_rel_id, trim($va_element_data['_relationship_type']), null, null, null, null, array('interstitialValues' => $va_element_data['_interstitial']));
                                 if ($vs_error = DataMigrationUtils::postError($t_subject, _t("[%1] Could not add related place with relationship %2:", $vs_idno, trim($va_element_data['_relationship_type'])), __CA_DATA_IMPORT_ERROR__, array('dontOutputLevel' => true, 'dontPrint' => true))) {
                                     ca_data_importers::logImportError($vs_error, $va_log_import_error_opts);
                                     if ($vs_item_error_policy == 'stop') {
                                         $o_log->logAlert(_t('Import stopped due to mapping error policy'));
                                         if ($vb_use_ncurses) {
                                             ncurses_end();
                                         }
                                         if ($o_trans) {
                                             $o_trans->rollback();
                                         }
                                         return false;
                                     }
                                 }
                             }
                             break;
                         case 'ca_collections':
                             if ($vn_rel_id = DataMigrationUtils::getCollectionID($va_element_data['preferred_labels']['name'], $va_element_data['_type'], $vn_locale_id, $va_data_for_rel_table, array('dontCreate' => $vb_dont_create, 'matchOn' => $va_match_on, 'log' => $o_log, 'transaction' => $o_trans, 'importEvent' => $o_event, 'importEventSource' => $vn_row, 'nonPreferredLabels' => $va_nonpreferred_labels))) {
                                 if (!($vs_rel_type = $va_element_data['_relationship_type']) && !($vs_rel_type = $va_element_data['idno']['_relationship_type'])) {
                                     break;
                                 }
                                 $t_subject->addRelationship($vs_table_name, $vn_rel_id, $vs_rel_type, null, null, null, null, array('interstitialValues' => $va_element_data['_interstitial']));
                                 if ($vs_error = DataMigrationUtils::postError($t_subject, _t("[%1] Could not add related collection with relationship %2:", $vs_idno, $vs_rel_type), __CA_DATA_IMPORT_ERROR__, array('dontOutputLevel' => true, 'dontPrint' => true))) {
                                     ca_data_importers::logImportError($vs_error, $va_log_import_error_opts);
                                     if ($vs_item_error_policy == 'stop') {
                                         $o_log->logAlert(_t('Import stopped due to mapping error policy'));
                                         if ($vb_use_ncurses) {
                                             ncurses_end();
                                         }
                                         if ($o_trans) {
                                             $o_trans->rollback();
                                         }
                                         return false;
                                     }
                                 }
                             }
                             break;
                         case 'ca_occurrences':
                             if ($vn_rel_id = DataMigrationUtils::getOccurrenceID($va_element_data['preferred_labels']['name'], $va_element_data['_parent_id'], $va_element_data['_type'], $vn_locale_id, $va_data_for_rel_table, array('dontCreate' => $vb_dont_create, 'matchOn' => $va_match_on, 'log' => $o_log, 'transaction' => $o_trans, 'importEvent' => $o_event, 'importEventSource' => $vn_row, 'nonPreferredLabels' => $va_nonpreferred_labels))) {
                                 if (!($vs_rel_type = $va_element_data['_relationship_type']) && !($vs_rel_type = $va_element_data['idno']['_relationship_type'])) {
                                     break;
                                 }
                                 $t_subject->addRelationship($vs_table_name, $vn_rel_id, $vs_rel_type, null, null, null, null, array('interstitialValues' => $va_element_data['_interstitial']));
                                 if ($vs_error = DataMigrationUtils::postError($t_subject, _t("[%1] Could not add related occurrence with relationship %2:", $vs_idno, $vs_rel_type), __CA_DATA_IMPORT_ERROR__, array('dontOutputLevel' => true, 'dontPrint' => true))) {
                                     ca_data_importers::logImportError($vs_error, $va_log_import_error_opts);
                                     if ($vs_item_error_policy == 'stop') {
                                         $o_log->logAlert(_t('Import stopped due to mapping error policy'));
                                         if ($vb_use_ncurses) {
                                             ncurses_end();
                                         }
                                         if ($o_trans) {
                                             $o_trans->rollback();
                                         }
                                         return false;
                                     }
                                 }
                             }
                             break;
                         case 'ca_storage_locations':
                             if ($vn_rel_id = DataMigrationUtils::getStorageLocationID($va_element_data['preferred_labels']['name'], $va_element_data['_parent_id'], $va_element_data['_type'], $vn_locale_id, $va_data_for_rel_table, array('dontCreate' => $vb_dont_create, 'matchOn' => $va_match_on, 'log' => $o_log, 'transaction' => $o_trans, 'importEvent' => $o_event, 'importEventSource' => $vn_row, 'nonPreferredLabels' => $va_nonpreferred_labels))) {
                                 if (!($vs_rel_type = $va_element_data['_relationship_type']) && !($vs_rel_type = $va_element_data['idno']['_relationship_type'])) {
                                     break;
                                 }
                                 $t_subject->addRelationship($vs_table_name, $vn_rel_id, trim($va_element_data['_relationship_type']), null, null, null, null, array('interstitialValues' => $va_element_data['_interstitial']));
                                 if ($vs_error = DataMigrationUtils::postError($t_subject, _t("[%1] Could not add related storage location with relationship %2:", $vs_idno, trim($va_element_data['_relationship_type'])), __CA_DATA_IMPORT_ERROR__, array('dontOutputLevel' => true, 'dontPrint' => true))) {
                                     ca_data_importers::logImportError($vs_error, $va_log_import_error_opts);
                                     if ($vs_item_error_policy == 'stop') {
                                         $o_log->logAlert(_t('Import stopped due to mapping error policy'));
                                         if ($vb_use_ncurses) {
                                             ncurses_end();
                                         }
                                         if ($o_trans) {
                                             $o_trans->rollback();
                                         }
                                         return false;
                                     }
                                 }
                             }
                             break;
                         case 'ca_list_items':
                             $va_data_for_rel_table['is_enabled'] = 1;
                             $va_data_for_rel_table['preferred_labels'] = $va_element_data['preferred_labels'];
                             if ($vn_rel_id = DataMigrationUtils::getListItemID($va_element_data['_list'], $va_element_data['idno'] ? $va_element_data['idno'] : null, $va_element_data['_type'], $vn_locale_id, $va_data_for_rel_table, array('dontCreate' => $vb_dont_create, 'matchOn' => $va_match_on, 'log' => $o_log, 'transaction' => $o_trans, 'importEvent' => $o_event, 'importEventSource' => $vn_row, 'nonPreferredLabels' => $va_nonpreferred_labels))) {
                                 if (!($vs_rel_type = $va_element_data['_relationship_type']) && !($vs_rel_type = $va_element_data['idno']['_relationship_type'])) {
                                     break;
                                 }
                                 $t_subject->addRelationship($vs_table_name, $vn_rel_id, trim($va_element_data['_relationship_type']), null, null, null, null, array('interstitialValues' => $va_element_data['_interstitial']));
                                 if ($vs_error = DataMigrationUtils::postError($t_subject, _t("[%1] Could not add related list item with relationship %2:", $vs_idno, trim($va_element_data['_relationship_type'])), __CA_DATA_IMPORT_ERROR__, array('dontOutputLevel' => true, 'dontPrint' => true))) {
                                     ca_data_importers::logImportError($vs_error, $va_log_import_error_opts);
                                     if ($vs_item_error_policy == 'stop') {
                                         $o_log->logAlert(_t('Import stopped due to mapping error policy'));
                                         if ($vb_use_ncurses) {
                                             ncurses_end();
                                         }
                                         if ($o_trans) {
                                             $o_trans->rollback();
                                         }
                                         return false;
                                     }
                                 }
                             }
                             break;
                         case 'ca_object_representations':
                             if ($vn_rel_id = DataMigrationUtils::getObjectRepresentationID($va_element_data['preferred_labels']['name'], $va_element_data['_type'], $vn_locale_id, $va_data_for_rel_table, array('dontCreate' => $vb_dont_create, 'matchOn' => $va_match_on, 'log' => $o_log, 'transaction' => $o_trans, 'importEvent' => $o_event, 'importEventSource' => $vn_row, 'nonPreferredLabels' => $va_nonpreferred_labels, 'matchMediaFilesWithoutExtension' => true))) {
                                 $t_subject->linkRepresentation($vn_rel_id, null, null, null, null, array('type_id' => trim($va_element_data['_relationship_type']), 'is_primary' => true));
                                 if ($vs_error = DataMigrationUtils::postError($t_subject, _t("[%1] Could not add related object representation with:", $vs_idno), __CA_DATA_IMPORT_ERROR__, array('dontOutputLevel' => true, 'dontPrint' => true))) {
                                     ca_data_importers::logImportError($vs_error, $va_log_import_error_opts);
                                     if ($vs_item_error_policy == 'stop') {
                                         $o_log->logAlert(_t('Import stopped due to mapping error policy'));
                                         if ($vb_use_ncurses) {
                                             ncurses_end();
                                         }
                                         if ($o_trans) {
                                             $o_trans->rollback();
                                         }
                                         return false;
                                     }
                                 }
                             }
                             //
                             // 									if (($vs_subject_table_name == 'ca_objects') && $va_element_data['media']['media']) {
                             // 										unset($va_data_for_rel_table['media']);
                             //
                             // 										foreach($va_data_for_rel_table as $vs_key => $vm_val) {
                             // 											// Attributes, including intrinsics are in two-level format, eg. idno is $va_attributes['idno']['idno']
                             // 											// but addRepresentations() expects intrinsics to be single level (eg. $va_attributes['idno']) so
                             // 											// we do some rewriting here
                             // 											if (is_array($vm_val) && isset($vm_val[$vs_key])) {
                             // 												$va_data_for_rel_table[$vs_key] = $vm_val[$vs_key];
                             // 											}
                             // 										}
                             //
                             // 										if (!($t_subject->addRepresentation($va_element_data['media']['media'], isset($va_element_data['_type']) ? $va_element_data['_type'] : caGetDefaultItemID('object_representation_types'), $vn_locale_id, 0, 0, true, $va_data_for_rel_table, array('dontCreate' => $vb_dont_create, 'matchOn' => $va_match_on)))) {
                             // 											$vs_error = join("; ", $t_subject->getErrors());
                             // 											ca_data_importers::logImportError($vs_error, $va_log_import_error_opts);
                             // 											if ($vs_item_error_policy == 'stop') {
                             // 												$o_log->logAlert(_t('Import stopped due to mapping error policy'));
                             // 												if($vb_use_ncurses) { ncurses_end(); }
                             // 												if ($o_trans) { $o_trans->rollback(); }
                             // 												return false;
                             // 											}
                             // 										}
                             // 									}
                             break;
                         case 'ca_loans':
                             if ($vn_rel_id = DataMigrationUtils::getLoanID($va_element_data['preferred_labels']['name'], $va_element_data['_type'], $vn_locale_id, $va_data_for_rel_table, array('dontCreate' => $vb_dont_create, 'matchOn' => $va_match_on, 'log' => $o_log, 'transaction' => $o_trans, 'importEvent' => $o_event, 'importEventSource' => $vn_row, 'nonPreferredLabels' => $va_nonpreferred_labels))) {
                                 if (!($vs_rel_type = $va_element_data['_relationship_type']) && !($vs_rel_type = $va_element_data['idno']['_relationship_type'])) {
                                     break;
                                 }
                                 $t_subject->addRelationship($vs_table_name, $vn_rel_id, trim($va_element_data['_relationship_type']), null, null, null, null, array('interstitialValues' => $va_element_data['_interstitial']));
                                 if ($vs_error = DataMigrationUtils::postError($t_subject, _t("[%1] Could not add related loan with relationship %2:", $vs_idno, trim($va_element_data['_relationship_type'])), __CA_DATA_IMPORT_ERROR__, array('dontOutputLevel' => true, 'dontPrint' => true))) {
                                     ca_data_importers::logImportError($vs_error, $va_log_import_error_opts);
                                     if ($vs_item_error_policy == 'stop') {
                                         $o_log->logAlert(_t('Import stopped due to mapping error policy'));
                                         if ($vb_use_ncurses) {
                                             ncurses_end();
                                         }
                                         if ($o_trans) {
                                             $o_trans->rollback();
                                         }
                                         return false;
                                     }
                                 }
                             }
                             break;
                         case 'ca_movements':
                             if ($vn_rel_id = DataMigrationUtils::getMovementID($va_element_data['preferred_labels']['name'], $va_element_data['_type'], $vn_locale_id, $va_data_for_rel_table, array('dontCreate' => $vb_dont_create, 'matchOn' => $va_match_on, 'log' => $o_log, 'transaction' => $o_trans, 'importEvent' => $o_event, 'importEventSource' => $vn_row, 'nonPreferredLabels' => $va_nonpreferred_labels))) {
                                 if (!($vs_rel_type = $va_element_data['_relationship_type']) && !($vs_rel_type = $va_element_data['idno']['_relationship_type'])) {
                                     break;
                                 }
                                 $t_subject->addRelationship($vs_table_name, $vn_rel_id, trim($va_element_data['_relationship_type']), null, null, null, null, array('interstitialValues' => $va_element_data['_interstitial']));
                                 if ($vs_error = DataMigrationUtils::postError($t_subject, _t("[%1] Could not add related movement with relationship %2:", $vs_idno, trim($va_element_data['_relationship_type'])), __CA_DATA_IMPORT_ERROR__, array('dontOutputLevel' => true, 'dontPrint' => true))) {
                                     ca_data_importers::logImportError($vs_error, $va_log_import_error_opts);
                                     if ($vs_item_error_policy == 'stop') {
                                         $o_log->logAlert(_t('Import stopped due to mapping error policy'));
                                         if ($vb_use_ncurses) {
                                             ncurses_end();
                                         }
                                         if ($o_trans) {
                                             $o_trans->rollback();
                                         }
                                         return false;
                                     }
                                 }
                             }
                             break;
                     }
                     if (is_array($va_element_data['_related_related']) && sizeof($va_element_data['_related_related'])) {
                         foreach ($va_element_data['_related_related'] as $vs_rel_rel_table => $va_rel_rels) {
                             foreach ($va_rel_rels as $vn_i => $va_rel_rel) {
                                 if (!($t_rel_instance = $o_dm->getInstanceByTableName($vs_table_name))) {
                                     $o_log->logWarn(_t("[%1] Could not instantiate related table %2", $vs_idno, $vs_table_name));
                                     continue;
                                 }
                                 if ($o_trans) {
                                     $t_rel_instance->setTransaction($o_trans);
                                 }
                                 if ($t_rel_instance->load($vn_rel_id)) {
                                     if ($t_rel_rel = $t_rel_instance->addRelationship($vs_rel_rel_table, $va_rel_rel['id'], $va_rel_rel['_relationship_type'])) {
                                         $o_log->logInfo(_t('[%1] Related %2 (%3) to related %4 with relationship %5', $vs_idno, $o_dm->getTableProperty($vs_rel_rel_table, 'NAME_SINGULAR'), $va_rel_rel['id'], $t_rel_instance->getProperty('NAME_SINGULAR'), trim($va_rel_rel['_relationship_type'])));
                                     } else {
                                         if ($vs_error = DataMigrationUtils::postError($t_subject, _t("[%1] Could not add related %2 (%3) to related %4 with relationship %5:", $vs_idno, $o_dm->getTableProperty($vs_rel_rel_table, 'NAME_SINGULAR'), $va_rel_rel['id'], $t_rel_instance->getProperty('NAME_SINGULAR'), trim($va_rel_rel['_relationship_type'])), __CA_DATA_IMPORT_ERROR__, array('dontOutputLevel' => true, 'dontPrint' => true))) {
                                             ca_data_importers::logImportError($vs_error, $va_log_import_error_opts);
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
         // $t_subject->update();
         //
         // 			if ($vs_error = DataMigrationUtils::postError($t_subject, _t("[%1] Invalid %2; values were %3: ", $vs_idno, 'attributes', ca_data_importers::formatValuesForLog($va_element_content)), __CA_DATA_IMPORT_ERROR__, array('dontOutputLevel' => true, 'dontPrint' => true))) {
         // 				ca_data_importers::logImportError($vs_error, $va_log_import_error_opts);
         // 				if ($vs_item_error_policy == 'stop') {
         // 					$o_log->logAlert(_t('Import stopped due to mapping error policy'));
         // 					if($vb_use_ncurses) { ncurses_end(); }
         //
         // 					$o_event->endItem($t_subject->getPrimaryKey(), __CA_DATA_IMPORT_ITEM_FAILURE__, _t('Failed to import %1', $vs_idno));
         //
         // 					if ($o_trans) { $o_trans->rollback(); }
         // 					return false;
         // 				}
         // 			}
         //
         $o_log->logDebug(_t('Finished inserting content tree for %1 at %2 seconds into database', $vs_idno, $t->getTime(4)));
         if (!$vb_output_subject_preferred_label && $t_subject->getPreferredLabelCount() == 0) {
             $t_subject->addLabel(array($vs_label_display_fld => '???'), $vn_locale_id, null, true);
             if ($vs_error = DataMigrationUtils::postError($t_subject, _t("[%1] Could not add default label", $vs_idno), __CA_DATA_IMPORT_ERROR__, array('dontOutputLevel' => true, 'dontPrint' => true))) {
                 ca_data_importers::logImportError($vs_error, $va_log_import_error_opts);
                 if ($vs_import_error_policy == 'stop') {
                     $o_log->logAlert(_t('Import stopped due to import error policy'));
                     if ($vb_use_ncurses) {
                         ncurses_end();
                     }
                     $o_event->endItem($t_subject->getPrimaryKey(), __CA_DATA_IMPORT_ITEM_FAILURE__, _t('Failed to import %1', $vs_idno));
                     if ($o_trans) {
                         $o_trans->rollback();
                     }
                     return false;
                 }
             }
         }
         $o_log->logInfo(_t('[%1] Imported %2 as %3 ', $vs_idno, $vs_preferred_label_for_log, $vs_subject_table_name));
         $o_event->endItem($t_subject->getPrimaryKey(), __CA_DATA_IMPORT_ITEM_SUCCESS__, _t('Imported %1', $vs_idno));
         ca_data_importers::$s_num_records_processed++;
     }
     $o_log->logInfo(_t('Import of %1 completed using mapping %2: %3 imported/%4 skipped/%5 errors', $ps_source, $t_mapping->get('importer_code'), ca_data_importers::$s_num_records_processed, ca_data_importers::$s_num_records_skipped, ca_data_importers::$s_num_import_errors));
     //if ($vb_show_cli_progress_bar) {
     $o_progress->finish();
     //}
     if ($po_request && isset($pa_options['progressCallback']) && ($ps_callback = $pa_options['progressCallback'])) {
         $ps_callback($po_request, $pn_file_number, $pn_number_of_files, $ps_source, $vn_num_items, $vn_num_items, _t('Import completed'), time() - $vn_start_time, memory_get_usage(true), ca_data_importers::$s_num_records_processed, ca_data_importers::$s_num_import_errors);
     }
     if (isset($pa_options['reportCallback']) && ($ps_callback = $pa_options['reportCallback'])) {
         $va_general = array('elapsedTime' => time() - $vn_start_time, 'numErrors' => ca_data_importers::$s_num_import_errors, 'numProcessed' => ca_data_importers::$s_num_records_processed);
         $ps_callback($po_request, $va_general, ca_data_importers::$s_import_error_list, true);
     }
     if ($vb_use_ncurses) {
         ncurses_end();
     }
     if ($pb_dry_run) {
         if ($o_trans) {
             $o_trans->rollback();
         }
         $o_log->logInfo(_t('Rollback successful import run in "dry run" mode'));
     } else {
         if ($o_trans) {
             $o_trans->commit();
         }
     }
     return true;
 }
Example #12
0
 function _strokeAllMenuItems(&$win)
 {
     for ($i = 0; $i < $this->menu_total; $i++) {
         if ($this->menu_cursor == $i) {
             ncurses_wcolor_set($win, 5);
         } else {
             ncurses_wcolor_set($win, 2);
         }
         // output Checkbox -- (optional)
         if ($this->mode == "checklist") {
             $sel = $this->menu_list[$i]['selected'] == true ? "û" : " ";
             ncurses_mvwaddstr($win, $this->menu_list[$i]['y'], $this->menu_list[$i]['x'], "[" . $sel . "]");
             ncurses_mvwaddstr($win, $this->menu_list[$i]['y'], $this->menu_list[$i]['x'] + 4, "");
             $desc_offset = 5;
         } else {
             ncurses_mvwaddstr($win, $this->menu_list[$i]['y'], $this->menu_list[$i]['x'], "");
             $desc_offset = 2;
         }
         // output menu item label
         $len = strlen($this->menu_list[$i]['label']);
         for ($n = 0; $n < $len; $n++) {
             $char = substr($this->menu_list[$i]['label'], $n, 1);
             $ord = ord($char);
             if ($char == $this->menu_list[$i]['hot']) {
                 if ($this->menu_cursor == $i) {
                     ncurses_wcolor_set($win, 6);
                 } else {
                     ncurses_wcolor_set($win, 7);
                 }
                 ncurses_wattron($win, NCURSES_A_BOLD);
                 ncurses_waddch($win, $ord);
                 ncurses_wattroff($win, NCURSES_A_BOLD);
             } else {
                 if ($this->menu_cursor == $i) {
                     ncurses_wcolor_set($win, 5);
                 } else {
                     ncurses_wcolor_set($win, 2);
                 }
                 ncurses_waddch($win, $ord);
             }
         }
         // output menu item description
         if ($this->menu_cursor == $i) {
             ncurses_wcolor_set($win, 5);
         } else {
             ncurses_wcolor_set($win, 2);
         }
         ncurses_mvwaddstr($win, $this->menu_list[$i]['y'], $this->menu_list[$i]['x'] + $this->menu_label_width + $desc_offset, $this->menu_list[$i]['desc']);
     }
 }
Example #13
0
 /**
  * Draws a string at current position
  * @param string $string String
  * @param integer $attributes Ncurses attributes (eg. NCURSES_A_REVERSE)
  * @see http://pubs.opengroup.org/onlinepubs/007908799/xcurses/curses.h.html for available attributes (WA_LOW => NCURSES_A_LOW)
  * @return Window This object
  */
 public function drawStringHere($string, $attributes = 0)
 {
     ncurses_wattron($this->windowResource, $attributes);
     ncurses_waddstr($this->windowResource, $string);
     ncurses_wattroff($this->windowResource, $attributes);
     return $this;
 }
Example #14
0
 /**
  * Prints a text to the pad
  * @param string $text text to print
  * @param int $color [optional] text color. One of the VarDumpNcurses::COLOR_* constants. Defaults to VarDumpNcurses::COLOR_DEFAULT.
  * @return int number of characters printed
  */
 protected function printRawText($text, $color = VarDumpNcurses::COLOR_DEFAULT)
 {
     if ($this->disablePrint) {
         return;
     }
     // if the line being printed is the one pointed by the cursor, highlight it
     if ($this->posY == $this->highlightedPositionY && $this->cursorHighlight) {
         $color += 10;
     }
     // verify if the color must be bolded
     $bold = false;
     if (in_array($color, $this->boldColorList)) {
         ncurses_wattron($this->pad, NCURSES_A_BOLD);
         $bold = true;
     }
     // print the text line by line
     // each line is checked for its visibility
     // we save the current Y position to be able to restore it
     $lines = explode("\n", $text);
     $nLines = count($lines);
     $posY = $this->posY;
     foreach ($lines as $k => $line) {
         if ($this->isBeingPrintedOutside(1)) {
             // the line is outside of the viewport
             // we increment the current Y position and skip drawing it
             $this->posY++;
             continue;
         } elseif ($k !== $nLines - 1) {
             // re-add the newline character for each line but the last
             $line .= "\n";
         }
         ncurses_wcolor_set($this->pad, $color);
         ncurses_waddstr($this->pad, $line);
         $this->posY++;
     }
     $this->posY = $posY;
     // unbold
     if ($bold) {
         ncurses_wattroff($this->pad, NCURSES_A_BOLD);
     }
     return strlen($text);
 }
Example #15
0
 /**
  * Prints a text to the pad
  * @param string $text text to print
  * @param int $color [optional] text color. One of the VarDumpNcurses::COLOR_* constants. Defaults to VarDumpNcurses::COLOR_DEFAULT.
  * @return int number of characters printed
  */
 protected function printRawText($text, $color = VarDumpNcurses::COLOR_DEFAULT)
 {
     if ($this->internalWriteEnabled) {
         return $this->printRawTextInternal($text);
     }
     // verify if the color must be bolded
     $bold = false;
     if (in_array($color, $this->boldColorList)) {
         ncurses_wattron($this->pad, NCURSES_A_BOLD);
         $bold = true;
     }
     // print the text
     ncurses_wcolor_set($this->pad, $color);
     ncurses_waddstr($this->pad, $text);
     // unbold
     if ($bold) {
         ncurses_wattroff($this->pad, NCURSES_A_BOLD);
     }
     return strlen($text);
 }
Example #16
0
 /**
  * Displays all Menu Items (or Checklist) to screen
  * @param $win
  */
 protected function strokeAllMenuItems(&$win)
 {
     for ($i = 0; $i < $this->menuTotal; $i++) {
         if ($this->menuCursor == $i) {
             ncurses_wcolor_set($win, 5);
         } else {
             ncurses_wcolor_set($win, 2);
         }
         // output Checkbox -- (optional)
         if ($this instanceof NcursesChecklist) {
             // for checklist type menus
             $sel = $this->menuList[$i]['selected'] == true ? 'X' : ' ';
             ncurses_mvwaddstr($win, $this->menuList[$i]['y'], $this->menuList[$i]['x'], '[' . $sel . ']');
             ncurses_mvwaddstr($win, $this->menuList[$i]['y'], $this->menuList[$i]['x'] + 4, '');
             $desc_offset = 5;
         } else {
             ncurses_mvwaddstr($win, $this->menuList[$i]['y'], $this->menuList[$i]['x'], '');
             $desc_offset = 2;
         }
         // output menu item label
         $len = strlen($this->menuList[$i]['label']);
         for ($n = 0; $n < $len; $n++) {
             $char = substr($this->menuList[$i]['label'], $n, 1);
             $ord = ord($char);
             if ($char == $this->menuList[$i]['hot']) {
                 // highlight char that is the hotkey
                 //SET HOTKEY COLOR ON SELECTED ITEM
                 if ($this->menuCursor == $i) {
                     ncurses_wcolor_set($win, 5);
                 } else {
                     ncurses_wcolor_set($win, 7);
                 }
                 ncurses_wattron($win, NCURSES_A_BOLD);
                 ncurses_waddch($win, $ord);
                 ncurses_wattroff($win, NCURSES_A_BOLD);
             } else {
                 if ($this->menuCursor == $i) {
                     ncurses_wcolor_set($win, 5);
                 } else {
                     ncurses_wcolor_set($win, 2);
                 }
                 ncurses_waddch($win, $ord);
             }
         }
         // output menu item description
         if ($this->menuCursor == $i) {
             ncurses_wcolor_set($win, 5);
         } else {
             ncurses_wcolor_set($win, 2);
         }
         ncurses_mvwaddstr($win, $this->menuList[$i]['y'], $this->menuList[$i]['x'] + $this->menuLabelWidth + $desc_offset, $this->menuList[$i]['desc']);
     }
 }
Example #17
0
EOT;
$lines = explode("\n", $quotes);
$n_lines = count($lines);
$window_width = 0;
for ($i = 0; $i < $n_lines; $i++) {
    $window_width = max($window_width, strlen($lines[$i]));
}
$window_width += 4;
$x_coords = array(10, 14, 18);
$y_coords = array(10, 12, 8);
for ($i = 0; $i < 3; $i++) {
    $windows[$i] = ncurses_newwin(4 + $n_lines, $window_width, $y_coords[$i], $x_coords[$i]);
    ncurses_wborder($windows[$i], 0, 0, 0, 0, 0, 0, 0, 0);
    ncurses_wattron($windows[$i], NCURSES_A_REVERSE);
    ncurses_mvwaddstr($windows[$i], 0, 2, ' window #' . $i . ' ');
    ncurses_wattroff($windows[$i], NCURSES_A_REVERSE);
    for ($j = 0; $j < $n_lines; $j++) {
        ncurses_mvwaddstr($windows[$i], 2 + $j, 2, $lines[$j]);
    }
    ncurses_wrefresh($windows[$i]);
    $panels[$i] = ncurses_new_panel($windows[$i]);
}
ncurses_update_panels();
ncurses_curs_set(0);
ncurses_noecho();
$i = 0;
$k = NULL;
while (XCURSES_KEY_ESC != $k) {
    $k = ncurses_getch();
    ncurses_top_panel($panels[$i % 3]);
    ncurses_update_panels();
Example #18
0
function ncurses_show_text($title, $text, $question, $keys = TRUE)
{
    // prepare text
    $textH = count($text);
    $textW = 1;
    $textLEN = array();
    for ($i = 0; $i < $textH; $i++) {
        $textLEN[$i] = strlen($text[$i]);
        if ($textLEN[$i] > $textW) {
            $textW = $textLEN[$i];
        }
    }
    // create text pad (invisible window)
    $textWIN = ncurses_newpad($textH, $textW);
    // fill it with text
    for ($i = 0; $i < $textH; $i++) {
        ncurses_mvwaddstr($textWIN, $i, 0, $text[$i]);
    }
    // prepare question
    $questionH = count($question);
    $questionLastW = strlen($question[$questionH - 1]);
    // initialize...
    $posX = $posY = 0;
    $screenH = $screenW = 0;
    // loop around...
    while (1) {
        // get actual screen size
        $oldH = $screenH;
        $oldW = $screenW;
        ncurses_getmaxyx(STDSCR, $screenH, $screenW);
        // something changed?
        if ($screenH != $oldH || $screenW != $oldW) {
            if ($oldH > 0) {
                ncurses_delwin($upperWIN);
                ncurses_delwin($lowerWIN);
            }
            ncurses_erase();
            ncurses_refresh(STDSCR);
            $upperWIN = ncurses_newwin($screenH - (2 + $questionH), $screenW, 0, 0);
            $lowerWIN = ncurses_newwin(2 + $questionH, $screenW, $screenH - (2 + $questionH), 0);
            $upperH = $screenH - (4 + $questionH);
            $upperW = $screenW - 2;
            $copyH = $upperH > $textH ? $textH : $upperH;
            $copyW = $upperW > $textW ? $textW : $upperW;
            // border lower window
            ncurses_wborder($lowerWIN, 0, 0, 0, 0, 0, 0, 0, 0);
            // print text in lower window
            for ($i = 0; $i < $questionH; $i++) {
                ncurses_mvwaddstr($lowerWIN, $i + 1, 1, $question[$i]);
            }
        }
        // check and fix positions
        if ($posY < 0 || $upperH >= $textH) {
            $posY = 0;
        } else {
            if ($upperH + $posY > $textH) {
                $posY = $textH - $upperH;
            }
        }
        if ($posX < 0 || $upperW >= $textW) {
            $posX = 0;
        } else {
            if ($upperW + $posX > $textW) {
                $posX = $textW - $upperW;
            }
        }
        // border upper window
        ncurses_wborder($upperWIN, 0, 0, 0, 0, 0, 0, 0, 0);
        // draw title and info line
        ncurses_wattron($upperWIN, NCURSES_A_REVERSE);
        ncurses_mvwaddstr($upperWIN, 0, 2, ' ' . $title . ' ');
        if ($upperH < $textH) {
            ncurses_mvwaddstr($upperWIN, $upperH + 1, 2, ' line ' . ($posY + 1) . '-' . ($posY + $copyH) . '/' . $textH . ' ');
        }
        ncurses_wattroff($upperWIN, NCURSES_A_REVERSE);
        // draw < and > at left/right side when horizontal scrolling is nesseccary
        if ($upperW < $textW) {
            for ($i = 0; $i < $copyH; $i++) {
                if ($textLEN[$i + $posY] > $copyW + $posX) {
                    ncurses_mvwaddstr($upperWIN, $i + 1, $screenW - 1, '>');
                }
                if ($posX > 0 && $textLEN[$i + $posY] > 0) {
                    ncurses_mvwaddstr($upperWIN, $i + 1, 0, '<');
                }
            }
        }
        // draw upper window
        ncurses_wrefresh($upperWIN);
        // copy a part of the text (pad) to the screen
        ncurses_prefresh($textWIN, $posY, $posX, 1, 1, $upperH, $upperW);
        // move cursor to end of last line of question
        ncurses_wmove($lowerWIN, $questionH, $questionLastW + 1);
        // draw lower window
        ncurses_wrefresh($lowerWIN);
        // get a character and do...
        $char = ncurses_getch();
        if (is_array($keys) && array_search($char, $keys) !== FALSE) {
            break;
        } else {
            if ($char == NCURSES_KEY_UP) {
                $posY--;
            } else {
                if ($char == NCURSES_KEY_DOWN) {
                    $posY++;
                } else {
                    if ($char == NCURSES_KEY_LEFT) {
                        $posX--;
                    } else {
                        if ($char == NCURSES_KEY_RIGHT) {
                            $posX++;
                        } else {
                            if ($char == NCURSES_KEY_PPAGE) {
                                $posY -= $copyH - 1;
                            } else {
                                if ($char == NCURSES_KEY_NPAGE) {
                                    $posY += $copyH - 1;
                                } else {
                                    if ($char == 362) {
                                        // HOME
                                        $posX = 0;
                                    } else {
                                        if ($char == 385) {
                                            // END
                                            $posX = 99999;
                                        } else {
                                            if ($char == 410 || $char == -1) {
                                                // these "characters" are pressed on resizing
                                            } else {
                                                if ($keys === TRUE) {
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    //end loop
    // free all resources
    ncurses_delwin($textWIN);
    ncurses_delwin($upperWIN);
    ncurses_delwin($lowerWIN);
    // return the pressed character
    return $char;
}
Example #19
0
function menu_select($params)
{
    ###################################################################################################
    if (!is_array($params) || empty($params)) {
        trigger_error('wrong params');
        return NULL;
    }
    $menu = isset($params['items']) ? $params['items'] : NULL;
    $rows = isset($params['rows']) ? (int) $params['rows'] : 0;
    $cols = isset($params['cols']) ? (int) $params['cols'] : 0;
    $selected = isset($params['selected']) ? (int) $params['selected'] : 0;
    $centered = empty($params['centered']) ? 0 : 1;
    $y_menu = isset($params['y']) ? (int) $params['y'] : 0;
    $x_menu = isset($params['x']) ? (int) $params['x'] : 0;
    if (!is_array($menu) || empty($menu) || $rows <= 0 || $cols <= 0 || $y_menu < 0 || $x_menu < 0) {
        trigger_error('wrong params');
        return NULL;
    }
    $keys = array_keys($menu);
    $values = array();
    $current = 0;
    $width = 0;
    $height = count($menu) + 2;
    foreach ($menu as $value) {
        $width = max($width, strlen($value));
    }
    $i = 0;
    foreach ($menu as $k => $v) {
        $values[$i] = ' ' . $v . str_repeat(' ', 1 + $width - strlen($v));
        if ($k == $selected) {
            $current = $i;
        }
        $i++;
    }
    $width += 4;
    if ($centered) {
        $y_menu = $rows - $height >> 1;
        $x_menu = $cols - $width >> 1;
    }
    $window = ncurses_newwin($height, $width, $y_menu, $x_menu);
    if (empty($window)) {
        trigger_error('unable to create window');
        return NULL;
    }
    ncurses_wborder($window, 0, 0, 0, 0, 0, 0, 0, 0);
    for ($a = 0; $a < count($values); $a++) {
        if ($a == $current) {
            ncurses_wattron($window, NCURSES_A_REVERSE);
        }
        ncurses_mvwaddstr($window, 1 + $a, 1, $values[$a]);
        if ($a == $current) {
            ncurses_wattroff($window, NCURSES_A_REVERSE);
        }
    }
    ncurses_wrefresh($window);
    ncurses_keypad($window, TRUE);
    ncurses_curs_set(0);
    do {
        $key = ncurses_wgetch($window);
        $move = 0;
        switch ($key) {
            case NCURSES_KEY_UP:
                if ($current > 0) {
                    $move = -1;
                }
                break;
            case NCURSES_KEY_DOWN:
                if ($current < count($values) - 1) {
                    $move = 1;
                }
                break;
            case XCURSES_KEY_LF:
            case XCURSES_KEY_CR:
                $result = $keys[$current];
                break;
            case XCURSES_KEY_ESC:
                ncurses_flushinp();
                $result = '';
                break;
        }
        if ($move) {
            ncurses_mvwaddstr($window, 1 + $current, 1, $values[$current]);
            $current += $move;
            ncurses_wattron($window, NCURSES_A_REVERSE);
            ncurses_mvwaddstr($window, 1 + $current, 1, $values[$current]);
            ncurses_wattroff($window, NCURSES_A_REVERSE);
            ncurses_wrefresh($window);
        }
    } while (!isset($result));
    ncurses_delwin($window);
    return $result;
}
Example #20
0
function dlg_input($params = array())
{
    ###############################################################################################
    $title = isset($params['title']) ? $params['title'] : NULL;
    $max_length = isset($params['max_len']) ? (int) $params['max_len'] : 10;
    $dlg_rows = isset($params['dlg_cols']) ? (int) $params['dlg_cols'] : 3;
    $dlg_cols = isset($params['dlg_cols']) ? (int) $params['dlg_cols'] : 40;
    $parent_cols = isset($params['cols']) ? (int) $params['cols'] : NULL;
    $parent_rows = isset($params['rows']) ? (int) $params['rows'] : NULL;
    $dlg_x = (int) (($parent_cols - $dlg_cols) / 2);
    if ($dlg_x < 0) {
        $dlg_x = 0;
    }
    $dlg_y = (int) (($parent_rows - $dlg_rows) / 2);
    if ($dlg_y < 0) {
        $dlg_y = 0;
    }
    if ($max_length <= 0 || $dlg_rows <= 0 || $dlg_cols <= 0) {
        trigger_error('wrong params');
        return NULL;
    }
    $dlg_window = ncurses_newwin($dlg_rows, $dlg_cols, $dlg_y, $dlg_x);
    if (empty($dlg_window)) {
        return NULL;
    }
    ncurses_wborder($dlg_window, 0, 0, 0, 0, 0, 0, 0, 0);
    if ($title) {
        ncurses_wattron($dlg_window, NCURSES_A_REVERSE);
        ncurses_mvwaddstr($dlg_window, 0, 2, ' ' . $title . ' ');
        ncurses_wattroff($dlg_window, NCURSES_A_REVERSE);
    }
    ncurses_curs_set(1);
    ncurses_wmove($dlg_window, 2, 2);
    ncurses_wrefresh($dlg_window);
    $do_getch = 1;
    $input_val = '';
    $input_char = '';
    $input_len = 0;
    $cursor_x = 2;
    $cursor_y = 1;
    ncurses_wmove($dlg_window, $cursor_y, $cursor_x);
    ncurses_noecho();
    ncurses_keypad($dlg_window, TRUE);
    while ($do_getch) {
        $key_code = ncurses_wgetch($dlg_window);
        if ($key_code == XCURSES_KEY_CR || $key_code == XCURSES_KEY_LF) {
            $do_getch = 0;
        } elseif ($key_code == NCURSES_KEY_BACKSPACE) {
            if ($input_len > 0) {
                $input_len--;
                $input_val = substr($input_val, 0, $input_len);
                $cursor_x--;
                ncurses_mvwaddstr($dlg_window, $cursor_y, $cursor_x, ' ');
                ncurses_wmove($dlg_window, $cursor_y, $cursor_x);
            }
        } elseif ($key_code < XCURSES_KEY_PRINTABLE_MIN || $key_code > XCURSES_KEY_PRINTABLE_MAX) {
            continue;
        } elseif ($input_len < $max_length) {
            $input_val .= $input_char = chr($key_code);
            $input_len++;
            $cursor_x++;
            ncurses_waddstr($dlg_window, $input_char);
        }
    }
    ncurses_delwin($dlg_window);
    return $input_val;
}
Example #21
0
function menu_check_list($params)
{
    ###############################################################################################
    if (!is_array($params) || empty($params)) {
        trigger_error('wrong_params');
        return NULL;
    }
    $menu = isset($params['items']) ? $params['items'] : NULL;
    $rows = isset($params['rows']) ? (int) $params['rows'] : 0;
    $cols = isset($params['cols']) ? (int) $params['cols'] : 0;
    $centered = empty($params['centered']) ? 0 : 1;
    $y_menu = isset($params['y']) ? (int) $params['y'] : 0;
    $x_menu = isset($params['x']) ? (int) $params['x'] : 0;
    if (!is_array($menu) || empty($menu) || $rows <= 0 || $cols <= 0 || $y_menu < 0 || $x_menu < 0) {
        trigger_error('wrong params');
        return NULL;
    }
    $keys = array_keys($menu);
    $n_menu = count($keys);
    $items = array();
    $checked = array();
    $current = 0;
    $width = 0;
    $height = $n_menu + 2;
    $i = 0;
    $k = NULL;
    $i_checked = NULL;
    for ($i = 0; $i < $n_menu; $i++) {
        $k = $keys[$i];
        $i_checked = isset($menu[$k][1]) && $menu[$k][1] == 1 ? 1 : 0;
        $items[$i] = ' [' . ($i_checked ? '*' : ' ') . '] ' . $menu[$k][0];
        $width = max($width, strlen($items[$i]));
        $checked[$i] = $i_checked;
    }
    for ($i = 0; $i < $n_menu; $i++) {
        $items[$i] = $items[$i] . str_repeat(' ', 2 + $width - strlen($items[$i]));
    }
    $width += 4;
    if ($centered) {
        $r = $rows - $height >> 1;
        $c = $cols - $width >> 1;
    }
    $window = ncurses_newwin($height, $width, $r, $c);
    if (empty($window)) {
        trigger_error('unable to create window');
        return NULL;
    }
    ncurses_wborder($window, 0, 0, 0, 0, 0, 0, 0, 0);
    $n_items = count($items);
    for ($i = 0; $i < $n_items; $i++) {
        if ($i == $current) {
            ncurses_wattron($window, NCURSES_A_REVERSE);
        }
        ncurses_mvwaddstr($window, 1 + $i, 1, $items[$i]);
        if ($i == $current) {
            ncurses_wattroff($window, NCURSES_A_REVERSE);
        }
    }
    ncurses_wrefresh($window);
    ncurses_keypad($window, TRUE);
    ncurses_noecho();
    ncurses_curs_set(0);
    $do_loop = 1;
    $save_result = 0;
    while ($do_loop) {
        $key = ncurses_wgetch($window);
        $move = 0;
        switch ($key) {
            case NCURSES_KEY_UP:
                if ($current > 0) {
                    $move = -1;
                }
                break;
            case NCURSES_KEY_DOWN:
                if ($current < $n_menu - 1) {
                    $move = 1;
                }
                break;
            case XCURSES_KEY_LF:
            case XCURSES_KEY_CR:
                $do_loop = 0;
                $save_result = 1;
                break;
            case XCURSES_KEY_SPACE:
                if ($checked[$current]) {
                    $checked[$current] = 0;
                    $items[$current] = ' [ ] ' . substr($items[$current], 5);
                } else {
                    $checked[$current] = 1;
                    $items[$current] = ' [*] ' . substr($items[$current], 5);
                }
                ncurses_wattron($window, NCURSES_A_REVERSE);
                ncurses_mvwaddstr($window, 1 + $current, 1, $items[$current]);
                ncurses_wattroff($window, NCURSES_A_REVERSE);
                ncurses_wrefresh($window);
                break;
            case XCURSES_KEY_ESC:
                ncurses_flushinp();
                $do_loop = 0;
                break;
        }
        if ($move) {
            ncurses_mvwaddstr($window, 1 + $current, 1, $items[$current]);
            $current += $move;
            ncurses_wattron($window, NCURSES_A_REVERSE);
            ncurses_mvwaddstr($window, 1 + $current, 1, $items[$current]);
            ncurses_wattroff($window, NCURSES_A_REVERSE);
            ncurses_wrefresh($window);
        }
    }
    ncurses_delwin($window);
    $result = NULL;
    if ($save_result) {
        for ($i = 0; $i < $n_menu; $i++) {
            $result[$keys[$i]] = $checked[$i];
        }
    }
    return $result;
}
 /**
  * {@inheritdoc}
  */
 protected function render()
 {
     if (null === $this->dataProfilerManager || 0 == count($this->dataProfilerManager)) {
         return;
     }
     foreach ($this->dataProfilerManager as $idProfiler => $profiler) {
         // retrieve current position
         $x = null;
         $y = null;
         ncurses_getyx($this->getPadResource(), $y, $x);
         // print profiler name and total execution time for that profiler
         $totalTime = count($profiler) ? $profiler->getTotalElapsedSecs() : 0;
         $totalTime = number_format($totalTime, 4, ".", " ");
         $title = $profiler->getDataSourceName() . " <<5>>(total execution time : {$totalTime} s)";
         $symbol = $this->isElementExpanded($idProfiler) ? "▾" : "▸";
         ncurses_wattron($this->getPadResource(), NCURSES_A_BOLD);
         $this->printText("<<4>>{$title} <<4>>{$symbol}\n");
         ncurses_wattroff($this->getPadResource(), NCURSES_A_BOLD);
         $this->setExpandableElementPositionY($idProfiler, $y);
         if (!$this->isElementExpanded($idProfiler)) {
             continue;
         }
         // print profiles
         if (count($profiler)) {
             foreach ($profiler as $i => $query) {
                 $this->printText("    ");
                 ncurses_wattron($this->getPadResource(), NCURSES_A_REVERSE);
                 $i = str_pad($i, 6, " ", STR_PAD_RIGHT);
                 $this->printText("<<6>>#{$i}\n");
                 ncurses_wattroff($this->getPadResource(), NCURSES_A_REVERSE);
                 // print query
                 $queryText = $profiler->getFormatter()->formatPlain($query->getQueryText());
                 $queryText = str_replace(array("\r\n", "\r"), "\n", $queryText);
                 $queryText = str_replace("\t", "    ", $queryText);
                 $queryText = explode("\n", $queryText);
                 foreach ($queryText as $queryLine) {
                     $this->printText("        {$queryLine}\n");
                 }
                 $this->printText(" \n");
                 // query params
                 if ($query->getQueryParams()) {
                     $maxLength = 0;
                     foreach ($query->getQueryParams() as $paramName => $paramValue) {
                         $maxLength = max($maxLength, strlen($paramName));
                     }
                     foreach ($query->getQueryParams() as $paramName => $paramValue) {
                         $paramType = "object" == gettype($paramValue) ? get_class($paramValue) : gettype($paramValue);
                         switch ($paramType) {
                             case "string":
                             case "integer":
                             case "long":
                             case "float":
                             case "double":
                                 // leave value as is
                                 break;
                             case "bool":
                             case "boolean":
                                 $paramValue = $paramValue ? "true" : "false";
                                 break;
                             case "null":
                             case "NULL":
                             case "array":
                             default:
                                 $paramValue = "";
                         }
                         $paramName = str_pad($paramName, $maxLength, " ", STR_PAD_RIGHT);
                         $this->printText("        <<5>>{$paramName} => <<2>>({$paramType}) <<5>>{$paramValue}\n");
                     }
                     $this->printText(" \n");
                 }
                 // query stats
                 $startTime = $query->getStartMicrotime() - $this->startMicrotime;
                 $endTime = $query->getEndMicrotime() ? $query->getEndMicrotime() - $this->startMicrotime : 0;
                 $queryTime = $this->formatQueryTime($startTime, $endTime);
                 $startMemory = $query->getStartMemoryUsage(true);
                 $endMemory = $query->getEndMemoryUsage(true);
                 $startPeakMemory = $query->getStartPeakMemoryUsage(true);
                 $endPeakMemory = $query->getEndPeakMemoryUsage(true);
                 $queryMemory = $this->formatQueryMemory($startMemory, $endMemory, "Memory usage");
                 $queryPeakMemory = $this->formatQueryMemory($startPeakMemory, $endPeakMemory, "Memory peak usage");
                 $queryStats = array("{$queryTime[0]} | {$queryMemory[0]} | {$queryPeakMemory[0]}", "{$queryTime[1]} | {$queryMemory[1]} | {$queryPeakMemory[1]}", "{$queryTime[2]} | {$queryMemory[2]} | {$queryPeakMemory[2]}", "{$queryTime[3]} |");
                 foreach ($queryStats as $statLine) {
                     $this->printText("        {$statLine}\n");
                 }
                 $this->printText(" \n");
             }
         }
     }
 }
Example #23
0
 public function setTitle($title)
 {
     $this->title = $title;
     ncurses_wattron($this->getWindow(), NCURSES_A_BOLD);
     ncurses_mvwaddstr($this->getWindow(), 0, 2, ' ' . $title . ' ');
     ncurses_wattroff($this->getWindow(), NCURSES_A_BOLD);
     $this->setChanged(true);
 }
Example #24
0
 $lower_frame_window = ncurses_newwin(10, $columns - 3, $lines - 11, 1);
 ncurses_wborder($lower_frame_window, 0, 0, 0, 0, 0, 0, 0, 0);
 // border it
 $lower_main_window = ncurses_newwin(8, $columns - 5, $lines - 10, 2);
 $main_list_window = ncurses_newwin($lines - 12, $columns - 3, 1, 1);
 ncurses_wborder($main_list_window, 0, 0, 0, 0, 0, 0, 0, 0);
 // border it
 if ($currently_selected == "") {
     $currently_selected = 0;
 }
 for ($a = 0; $a < count($tr_return); $a++) {
     $out = $tr_return[$a];
     if ($currently_selected == intval($a)) {
         ncurses_wattron($main_list_window, NCURSES_A_REVERSE);
         ncurses_mvwaddstr($main_list_window, 1 + $a, 1, $out);
         ncurses_wattroff($main_list_window, NCURSES_A_REVERSE);
     } else {
         ncurses_mvwaddstr($main_list_window, 1 + $a, 1, $out);
     }
 }
 if ($y == ENTER_KEY) {
     $newout = explode(" ", $check_me);
     $rwhois_return = rwhois(trim($newout[3]));
     $a = 0;
     while (list($key, $val) = each($rwhois_return)) {
         ncurses_mvwaddstr($lower_main_window, 1 + $a, 1, $key . " - " . $val);
         $a++;
     }
 } elseif ($y == ESCAPE_KEY) {
     ncurses_end();
     exit;
Example #25
0
 /**
  * Refresh the footer window
  */
 protected function refreshFooter()
 {
     $length = 1;
     $labels = array("F1" => "Help", "F2" => "Var dump", "F3" => "Stack trace", "Q" => "Quit");
     if (null === $this->rendererStackTrace) {
         unset($labels["F3"]);
     }
     ncurses_werase($this->windowFooter);
     // write an empty space
     ncurses_wattron($this->windowFooter, NCURSES_A_REVERSE);
     ncurses_wcolor_set($this->windowFooter, NCURSES_COLOR_CYAN);
     ncurses_waddstr($this->windowFooter, " ");
     ncurses_wattroff($this->windowFooter, NCURSES_A_REVERSE);
     // write key/labels
     foreach ($labels as $key => $label) {
         ncurses_wcolor_set($this->windowFooter, 0);
         ncurses_waddstr($this->windowFooter, $key);
         ncurses_wattron($this->windowFooter, NCURSES_A_REVERSE);
         ncurses_wcolor_set($this->windowFooter, NCURSES_COLOR_CYAN);
         ncurses_waddstr($this->windowFooter, "{$label} ");
         ncurses_wattroff($this->windowFooter, NCURSES_A_REVERSE);
         $length += strlen($key);
         $length += strlen($label);
         $length += 1;
     }
     // fill the line
     $fillStr = str_repeat(" ", $this->windowFooterWidth - $length);
     ncurses_wattron($this->windowFooter, NCURSES_A_REVERSE);
     ncurses_wcolor_set($this->windowFooter, NCURSES_COLOR_CYAN);
     ncurses_waddstr($this->windowFooter, $fillStr);
     ncurses_wattroff($this->windowFooter, NCURSES_A_REVERSE);
     ncurses_wrefresh($this->windowFooter);
 }
Example #26
0
 /**
  * Draws the menu on the workspace.
  *
  * @param int $workspace The workspace window handle for curses
  */
 function draw($workspace)
 {
     $wh = $this->_wh;
     ncurses_wcolor_set($wh, NCC_FRAME);
     ncurses_wborder($wh, 0, 0, 0, 0, 0, 0, 0, 0);
     ncurses_wcolor_set($wh, NCC_TITLE);
     ncurses_wattron($wh, NCURSES_A_BOLD);
     $left = floor(($this->_w - 2) / 2 - (strlen($this->_title) + 2) / 2);
     ncurses_mvwaddstr($wh, 0, $left, ' ' . $this->_title . ' ');
     ncurses_wattroff($wh, NCURSES_A_BOLD);
     ncurses_wcolor_set($wh, NCC_TEXT);
     $i = $this->_scroll;
     $sm = count($this->_items) - ($this->_h - 2);
     if ($sm < 0) {
         $sm = 0;
     }
     for ($n = 0; $n < $this->_h - 2; $n++) {
         if ($n + $i < count($this->_items)) {
             $str = " " . $this->_itemsidx[$n + $i];
         } else {
             $str = "";
         }
         $str .= str_repeat(' ', $this->_w - 2 - strlen($str));
         if ($n + $i == $this->_selected) {
             ncurses_wattron($wh, NCURSES_A_REVERSE);
         }
         $str = substr($str, 0, $this->_w - 2);
         ncurses_mvwaddstr($wh, $n + 1, 1, $str);
         ncurses_wattroff($wh, NCURSES_A_REVERSE);
     }
     ncurses_wcolor_set($wh, NCC_MORE);
     if ($i > 0) {
         ncurses_wmove($wh, 1, $this->_w - 1);
         ncurses_waddch($wh, NCURSES_ACS_UARROW | NCURSES_A_BOLD);
     }
     if ($sm - $i > 0) {
         ncurses_wmove($wh, $this->_h - 2, $this->_w - 1);
         ncurses_waddch($wh, NCURSES_ACS_DARROW | NCURSES_A_BOLD);
     }
     ncurses_wrefresh($wh);
     ncurses_wcolor_set($wh, 0);
     ncurses_move(-1, 1);
     ncurses_refresh();
 }
Example #27
0
function dialog($params)
{
    ###############################################################################################
    if (empty($params) || !is_array($params)) {
        trigger_error('params must be non-empty array');
        return NULL;
    }
    $message = isset($params['message']) ? $params['message'] : '';
    $buttons = !empty($params['buttons']) && is_array($params['buttons']) ? $params['buttons'] : array('OK');
    $n_buttons = count($buttons);
    for ($i = 0; $i < $n_buttons; $i++) {
        $buttons[$i] = ' ' . $buttons[$i] . ' ';
    }
    $parent_rows = isset($params['rows']) && $params['rows'] > 0 ? (int) $params['rows'] : 25;
    $parent_cols = isset($params['cols']) && $params['cols'] > 0 ? (int) $params['cols'] : 80;
    if (empty($message) || empty($buttons) || $parent_rows <= 0 || $parent_cols <= 0) {
        trigger_error('wrong params');
        return NULL;
    }
    $message_lines = split("\n", $message);
    $message_width = 0;
    $n_message_lines = count($message_lines);
    for ($i = 0; $i < $n_message_lines; $i++) {
        $message_width = max(strlen($message_lines[$i]), $message_width);
    }
    $buttons_delim = '  ';
    $buttons_delim_len = strlen($buttons_delim);
    $buttons_len = strlen(implode($buttons_delim, $buttons));
    $width = 4 + max($buttons_len + 2 * $buttons_delim_len, $message_width);
    $height = 4 + $n_message_lines;
    $dlg_y = $parent_rows > $height ? $parent_rows - $height >> 1 : 1;
    $dlg_x = $parent_cols > $width ? $parent_cols - $width >> 1 : 1;
    $window = ncurses_newwin($height, $width, $dlg_y, $dlg_x);
    if (empty($window)) {
        trigger_error('unable to create window');
        return NULL;
    }
    ncurses_wborder($window, 0, 0, 0, 0, 0, 0, 0, 0);
    $i_x = 0;
    $i_y = 0;
    for ($i = 0; $i < $n_message_lines; $i++) {
        $i_y = 1 + $i;
        $i_x = 1 + ($width - 2 - strlen($message_lines[$i]) >> 1);
        ncurses_mvwaddstr($window, $i_y, $i_x, rtrim($message_lines[$i]));
    }
    $buttons_data = array();
    $buttons_shift_x = 1 + ($width - 1 - $buttons_len >> 1);
    $buttons_shift_y = 2 + $n_message_lines;
    $i_title = '';
    $i_x = $buttons_shift_x;
    for ($i = 0; $i < $n_buttons; $i++) {
        $i_title = $buttons[$i];
        $buttons_data[] = array('x' => $i_x, 's' => $i_title);
        if (0 == $i) {
            ncurses_wattron($window, NCURSES_A_REVERSE);
        }
        ncurses_mvwaddstr($window, $buttons_shift_y, $i_x, $i_title);
        if (0 == $i) {
            ncurses_wattroff($window, NCURSES_A_REVERSE);
        }
        $i_x += strlen($i_title) + $buttons_delim_len;
    }
    ncurses_wrefresh($window);
    ncurses_keypad($window, TRUE);
    ncurses_curs_set(0);
    ncurses_noecho();
    $result = -1;
    $do_loop = 1;
    $move = 0;
    $current = 0;
    while ($do_loop) {
        $key = ncurses_wgetch($window);
        $move = 0;
        switch ($key) {
            case NCURSES_KEY_LEFT:
                if ($current > 0) {
                    $move = -1;
                }
                break;
            case NCURSES_KEY_RIGHT:
                if ($current < $n_buttons - 1) {
                    $move = 1;
                }
                break;
            case XCURSES_KEY_LF:
            case XCURSES_KEY_CR:
                $result = $current;
                $do_loop = 0;
                break;
            case XCURSES_KEY_ESC:
                $do_loop = 0;
                break;
        }
        if (0 == $do_loop) {
            ncurses_flushinp();
        } elseif ($move) {
            ncurses_mvwaddstr($window, $buttons_shift_y, $buttons_data[$current]['x'], $buttons_data[$current]['s']);
            $current += $move;
            ncurses_wattron($window, NCURSES_A_REVERSE);
            ncurses_mvwaddstr($window, $buttons_shift_y, $buttons_data[$current]['x'], $buttons_data[$current]['s']);
            ncurses_wattroff($window, NCURSES_A_REVERSE);
            ncurses_wrefresh($window);
        }
    }
    ncurses_delwin($window);
    return $result;
}
Example #28
0
     }
     $ligne++;
 }
 $result = pg_query($db, "select count(*) as nb_sonde, sum(case when date_trunc('minute', last_update) = (select date_trunc('minute', max(last_update)) from onewire) then 1 else 0 end ) as nb_sonde_ok,  sum(case when date_trunc('minute', last_update) != (select date_trunc('minute', max(last_update)) from onewire) then 1 else 0 end ) as nb_sonde_ko, date_trunc('minute', max(last_update)) as last_update, case when (select date_trunc('minute', max(last_update)) from onewire) < current_timestamp - interval '1 min' then 1 else 0 end as alerte, current_timestamp - interval '1 min' from onewire;") or die('Erreur SQL sur recuperation des valeurs: ' . pg_error());
 $maj = pg_fetch_array($result);
 if ($maj['nb_sonde_ok'] == $maj['nb_sonde']) {
     ncurses_mvwaddstr($bl, 13, 2, "Maj : ");
     ncurses_wcolor_set($bl, 2);
     ncurses_mvwaddstr($bl, 13, 8, $maj['last_update'] . " " . $maj['nb_sonde_ok'] . "/" . $maj['nb_sonde'] . " sondes");
     ncurses_wcolor_set($bl, 0);
 } else {
     ncurses_mvwaddstr($bl, 13, 2, "Maj : ");
     ncurses_wattron($bl, NCURSES_A_BOLD);
     ncurses_wcolor_set($bl, 1);
     ncurses_mvwaddstr($bl, 13, 8, $maj['last_update'] . " " . $maj['nb_sonde_ok'] . "/" . $maj['nb_sonde'] . " sondes");
     ncurses_wattroff($bl, NCURSES_A_BOLD);
     ncurses_wcolor_set($bl, 0);
 }
 // nb_sonde | nb_sonde_ok | nb_sonde_ko |     last_update     | alerte |           ?column?
 //----------+-------------+-------------+---------------------+--------+-------------------------------
 //       35 |          35 |           0 | 2013-04-29 23:10:02 |      0 | 2013-04-29 21:11:27.299489+00
 /*
 $tmp=9;
 ncurses_wcolor_set($bl, 1);
 ncurses_mvwaddstr($bl, $tmp, 2, "RED");
 ncurses_wcolor_set($bl, 2);
 ncurses_mvwaddstr($bl, $tmp, 6, "GREEN");
 ncurses_wcolor_set($bl, 3);
 ncurses_mvwaddstr($bl, $tmp, 12, "YELLOW");
 ncurses_wcolor_set($bl, 4);
 ncurses_mvwaddstr($bl, $tmp, 19, "BLUE");