void WindowCheckKeyterms::html_link_clicked (const gchar * url)
{
  // Store scrolling position for the now active url.
  GtkAdjustment * adjustment = gtk_scrolled_window_get_vadjustment (GTK_SCROLLED_WINDOW (scrolledwindow_terms));
  scrolling_position[active_url] = gtk_adjustment_get_value (adjustment);

  // New url.
  active_url = url;

  // Whether to show some widgets.
  bool show_collections = false;
  bool show_renderings = false;
    
  // Start writing a html page.
  HtmlWriter2 htmlwriter ("");
  bool display_another_page = false;

  if (active_url.find (_("keyterm ")) == 0) {
    // Store url of this keyterm.
    last_keyword_url = active_url;
    // Get the keyterm identifier.
    ustring url = active_url;
    url.erase (0, 8);
    keyword_id = convert_to_int (url);
    // Load the renderings. 
    // To be done before displaying the verses themselves since the latter depends on the former.
    load_renderings ();
    // Write extra bits.
    html_write_keyterms (htmlwriter, keyword_id);
    show_renderings = true;
    display_another_page = true;
  }

  else if (active_url.find (_("goto ")) == 0) {
    // Signal the editors to go to a reference.
    ustring url = active_url;
    url.erase (0, 5);
    myreference.assign (get_reference (url));
    new_reference_showing = &myreference;
    gtk_button_clicked(GTK_BUTTON(signal));
  }
  
  else if (active_url.find (_("send")) == 0) {
    // Send the references to the references window.
    ustring url = active_url;
    new_reference_showing = NULL;
    gtk_button_clicked(GTK_BUTTON(signal));
  }
  
  else {
    // Give the starting page with all keyterms of the active selection.
    show_collections = true;
    if (collection().find (_("Biblical")) != string::npos) {
      if (collection().find (_("Hebrew")) != string::npos) {
        htmlwriter.paragraph_open ();
        htmlwriter.text_add (_("Key Terms in Biblical Hebrew: The entries are an experimental sample set, not yet fully reviewed and approved. The KTBH team would welcome feed-back to [email protected]"));
        htmlwriter.paragraph_close ();
      }
    }
    vector <ustring> terms;
    vector <unsigned int> ids;
    keyterms_get_terms("", collection(), terms, ids);
    for (unsigned int i = 0; i < terms.size(); i++) {
      htmlwriter.paragraph_open();
      htmlwriter.hyperlink_add (_("keyterm ") + convert_to_string (ids[i]), terms[i]);
      htmlwriter.paragraph_close();
    }
    display_another_page = true;
    // No renderings.
    clear_renderings ();
  }
  
  htmlwriter.finish();
  if (display_another_page) {
    // Load the page.
    webkit_web_view_load_string (WEBKIT_WEB_VIEW (webview_terms), htmlwriter.html.c_str(), NULL, NULL, NULL);
    // Scroll to the position that possibly was stored while this url was last active.
    GtkAdjustment * adjustment = gtk_scrolled_window_get_vadjustment (GTK_SCROLLED_WINDOW (scrolledwindow_terms));
    gtk_adjustment_set_value (adjustment, scrolling_position[active_url]);
    // Whether to show collections.
    if (show_collections)
      gtk_widget_show (hbox_collection);
    else
      gtk_widget_hide (hbox_collection);
    if (show_renderings)
      gtk_widget_show (treeview_renderings);
    else
      gtk_widget_hide (treeview_renderings);
  }
}
Example #2
0
string notes_actions (void * webserver_request)
{
  Webserver_Request * request = (Webserver_Request *) webserver_request;
  Database_Notes database_notes (webserver_request);
  Notes_Logic notes_logic = Notes_Logic (webserver_request);

  
  string page;
  Assets_Header header = Assets_Header (translate("Note actions"), request);
  header.setNavigator ();
  page += header.run ();
  Assets_View view;
  string success, error;

  
  string user = request->session_logic()->currentUser ();
  int level = request->session_logic()->currentLevel ();

  
  int id;
  if (request->query.count ("id")) id = convert_to_int (request->query ["id"]);
  else id = convert_to_int (request->post ["id"]);

  
  if (request->query.count ("unsubscribe")) {
    notes_logic.unsubscribe (id);
  }
  
  
  if (request->query.count ("subscribe")) {
    notes_logic.subscribe (id);
  }
  
  
  if (request->query.count ("unassign")) {
    string unassign = request->query["unassign"];
    notes_logic.unassignUser (id, unassign);
  }
  
  
  if (request->query.count ("done")) {
    notes_logic.unassignUser (id, user);
  }
  
  
  if (request->query.count ("markdel")) {
    notes_logic.markForDeletion (id);
    success = translate("The note will be deleted after a week.") + " " + translate ("Adding a comment to the note cancels the deletion.");
  }
  
  
  if (request->query.count ("unmarkdel")) {
    notes_logic.unmarkForDeletion (id);
  }
  
  
  if (request->query.count ("delete")) {
    notes_logic.erase (id);
    redirect_browser (request, notes_index_url ());
    return "";
  }
  
  
  if (request->query.count ("publicnote")) {
    bool state = database_notes.getPublic (id);
    database_notes.setPublic (id, !state);
  }

  
  view.set_variable ("id", convert_to_string (id));
  
                      
  string summary = database_notes.getSummary (id);
  view.set_variable ("summary", summary);
                                          
                                          
  bool subscribed = database_notes.isSubscribed (id, user);
  if (subscribed) view.enable_zone ("subscribed");
  else view.enable_zone ("subscribe");
  

  vector <string> assignees = database_notes.getAssignees (id);
  string assigneeblock;
  for (auto & assignee : assignees) {
    assigneeblock.append (assignee);
    if (level >= Filter_Roles::manager ()) {
      assigneeblock.append ("<a href=\"?id=" + convert_to_string (id) + "&unassign=" + assignee + "\"> [" + translate("unassign") + "]</a>");
      assigneeblock.append (" | ");
    }
  }
  view.set_variable ("assigneeblock", assigneeblock);
  if (level >= Filter_Roles::manager ()) view.enable_zone ("assign");

  
  bool assigned = database_notes.isAssigned (id, user);
  if (assigned) view.enable_zone ("assigned");
  
  
  string status = database_notes.getStatus (id);
  view.set_variable ("status", status);
  if (Filter_Roles::translator ()) view.enable_zone ("editstatus");
  else view.enable_zone ("viewstatus");

  
  string verses = filter_passage_display_inline (database_notes.getPassages (id));
  view.set_variable ("verses", verses);
                                          
                                          
  string severity = database_notes.getSeverity (id);
  view.set_variable ("severity",  severity);

  
  string bible = database_notes.getBible (id);
  view.set_variable ("bible", bible);
  if (bible.empty ()) view.enable_zone ("nobible");

  
  if (level >= Filter_Roles::manager ()) view.enable_zone ("rawedit");
  

  if (level >= Filter_Roles::manager ()) view.enable_zone ("marknote");
  bool marked = database_notes.isMarkedForDeletion (id);
  if (marked) view.enable_zone ("marked");
  else view.enable_zone ("mark");
  
  
#ifndef HAVE_CLIENT
  view.enable_zone ("cloud");
  string on_off = styles_logic_off_on_inherit_toggle_text (database_notes.getPublic (id));
  view.set_variable ("publicnote", on_off);
#endif
  // Roles of translator or higher can edit the public visibility of a note.
  if (level >= Filter_Roles::translator ()) view.enable_zone ("translator");

  
  view.set_variable ("success", success);
  view.set_variable ("error", error);
  page += view.render ("notes", "actions");
  page += Assets_Page::footer ();
  return page;
}
Example #3
0
void git_resolve_conflicts(const ustring & project, const vector < ustring > &errors)
/*
 This function reads through the "errors" to see if any conflicting merge occurred.
 If that happened, it resolves the conflicts.
 */
{
  /*
     See if the errors indicate a conflict. If not, bail out.

     The first time that a "git pull" is done, and there is a conflict, it says this:

     Auto-merged 3 John/1/data
     CONFLICT (content): Merge conflict in 3 John/1/data
     Automatic merge failed; fix conflicts and then commit the result.  

     The second time that a "git pull" would be done, it would say this:

     You are in the middle of a conflicted merge.

   */
  bool conflict = false;
  for (unsigned int i = 0; i < errors.size(); i++) {
    if (errors[i].find("conflict") != string::npos) {
      conflict = true;
    }
  }
  if (!conflict)
    return;

  // Get the working directory.
  ustring directory = project_data_directory_project(project);

  // Run a "git status" to find the books and chapters that have a merge conflict.
  vector < Reference > conflicted_chapters;
  {
    GwSpawn spawn("git status");
    spawn.workingdirectory(directory);
    spawn.read();
    spawn.run();
    for (unsigned int i = 0; i < spawn.standardout.size(); i++) {
      ustring line = spawn.standardout[i];
      size_t pos = line.find("unmerged:");
      if (pos != string::npos) {
        line.erase(0, pos + 10);
        line = trim(line);
        Parse parse(line, false, G_DIR_SEPARATOR_S);
        if (parse.words.size() >= 2) {
          unsigned int book = books_english_to_id(parse.words[0]);
          if (book) {
            unsigned int chapter = convert_to_int(parse.words[1]);
            Reference reference(book, chapter, "");
            conflicted_chapters.push_back(reference);
          }
        }
      }
    }
  }

  // Resolve all conflicts according to the settings of the user.
  for (unsigned int i = 0; i < conflicted_chapters.size(); i++) {
    git_resolve_conflict_chapter(project, conflicted_chapters[i].book_get(), conflicted_chapters[i].chapter_get());
  }

  // Commit the changes.
  {
    GwSpawn spawn("git commit");
    spawn.workingdirectory(directory);
    spawn.arg("-m");
    spawn.arg("Resolved conflict");
    spawn.arg("-a");
    spawn.run();
  }
}
Example #4
0
int Database_Config_General::getIValue (const char * key, int default_value)
{
  string value = getValue (key, convert_to_string (default_value).c_str());
  return convert_to_int (value);
}
Example #5
0
string resource_get (void * webserver_request)
{
    Webserver_Request * request = (Webserver_Request *) webserver_request;


    vector <string> bits;


    string s_resource = request->query["resource"];
    string s_book = request->query["book"];
    string s_chapter = request->query["chapter"];
    string s_verse = request->query["verse"];


    if (!s_resource.empty () && !s_book.empty () && !s_chapter.empty () && !s_verse.empty ()) {


        unsigned int resource = convert_to_int (s_resource);
        int book = convert_to_int (s_book);
        int chapter = convert_to_int (s_chapter);
        int verse = convert_to_int (s_verse);


        // In JavaScript the resource identifier starts at 1 instead of at 0.
        resource--;
        vector <string> resources = request->database_config_user()->getActiveResources ();
        if (resource <= resources.size ()) {
            s_resource = resources [resource];


            // Handle a divider.
            if (resource_logic_is_divider (s_resource)) return resource_logic_get_divider (s_resource);


            string bible = request->database_config_user ()->getBible ();
            string versification = Database_Config_Bible::getVersificationSystem (bible);
            Database_Versifications database_versifications;
            vector <int> chapters = database_versifications.getChapters (versification, book);


            // Whether to add extra verse numbers, for clarity in case of viewing more than one verse.
            bool add_verse_numbers = false;
            int context_before = request->database_config_user ()->getResourceVersesBefore ();
            if (context_before) add_verse_numbers = true;
            int context_after = request->database_config_user ()->getResourceVersesAfter ();
            if (context_after) add_verse_numbers = true;


            // Context before the focused verse.
            vector <int> chapters_before;
            vector <int> verses_before;
            if (context_before > 0) {
                for (int ch = chapter - 1; ch <= chapter; ch++) {
                    if (in_array (ch, chapters)) {
                        vector <int> verses = database_versifications.getVerses (versification, book, ch);
                        for (size_t vs = 0; vs < verses.size (); vs++) {
                            int vs2 = verses [vs];
                            if ((ch < chapter) || (vs2 < verse)) {
                                if (vs2 > 0) {
                                    chapters_before.push_back (ch);
                                    verses_before.push_back (verses[vs]);
                                }
                            }
                        }
                    }
                }
                while ((int)chapters_before.size () > context_before) {
                    chapters_before.erase (chapters_before.begin ());
                    verses_before.erase (verses_before.begin ());
                }
            }
            for (unsigned int i = 0; i < chapters_before.size (); i++) {
                bits.push_back (resource_logic_get_html (request, s_resource, book, chapters_before[i], verses_before[i], add_verse_numbers));
            }


            // Focused verse.
            bits.push_back (resource_logic_get_html (request, s_resource, book, chapter, verse, add_verse_numbers));


            // Context after the focused verse.
            vector <int> chapters_after;
            vector <int> verses_after;
            if (context_after > 0) {
                for (int ch = chapter; ch <= chapter + 1; ch++) {
                    if (in_array (ch, chapters)) {
                        vector <int> verses = database_versifications.getVerses (versification, book, ch);
                        for (size_t vs = 0; vs < verses.size (); vs++) {
                            int vs2 = verses [vs];
                            if ((ch > chapter) || (vs2 > verse)) {
                                if (vs2 > 0) {
                                    chapters_after.push_back (ch);
                                    verses_after.push_back (verses[vs]);
                                }
                            }
                        }
                    }
                }
                while ((int)chapters_after.size () > context_after) {
                    chapters_after.pop_back ();
                    verses_after.pop_back ();
                }
            }
            for (unsigned int i = 0; i < chapters_after.size (); i++) {
                bits.push_back (resource_logic_get_html (request, s_resource, book, chapters_after[i], verses_after[i], add_verse_numbers));
            }
        }
    }


    string page = filter_string_implode (bits, ""); // <br>
    return page;
}
Example #6
0
string lexicon_definition (void * webserver_request)
{
  // Retrieve the id: It may contain a Strong's number or a lemma.
  Webserver_Request * request = (Webserver_Request *) webserver_request;
  string id = request->query["id"];
  
  vector <string> renderings;
  
  if (!id.empty ()) {
    
    string letter = id.substr (0, 1);
    if (letter == HEBREW_ETCBC4_PREFIX) {
      
      // ETCBC4 database.
      // When a defintion is clicked for the second time, it gets erased.
      if (id != request->database_config_user ()->getRequestedEtcbc4Definition ()) {
        renderings.push_back (lexicon_logic_render_etcbc4_morphology (id));
      } else {
        id.clear ();
      }
      request->database_config_user ()->setRequestedEtcbc4Definition (id);
                                                                
    } else if (letter == KJV_LEXICON_PREFIX) {
      
      // King James Bible with Strong's numbers.
      if (id != request->database_config_user ()->getRequestedKjvDefinition ()) {
        Database_Kjv database_kjv;
        string strong = database_kjv.strong (convert_to_int (id.substr (1)));
        string rendering = lexicon_logic_render_definition (strong);
        if (!rendering.empty ()) renderings.push_back (rendering);
      } else {
        id.clear ();
      }
      request->database_config_user ()->setRequestedKjvDefinition (id);
      
    } else if (letter == MORPHHB_PREFIX) {
      
      // Open Scriptures Hebrew with Strong's numbers.
      if (id != request->database_config_user ()->getRequestedMorphHbDefinition ()) {
        Database_MorphHb database_morphhb;
        string parsing = database_morphhb.parsing (convert_to_int (id.substr (1)));
        vector <string> strongs;
        vector <string> bdbs;
        lexicon_logic_convert_morphhb_parsing_to_strong (parsing, strongs, bdbs);
        for (size_t i = 0; i < strongs.size (); i++) {
          string rendering = lexicon_logic_render_definition (strongs[i]);
          if (!rendering.empty ()) renderings.push_back (rendering);
          rendering = "<a href=\"" BDB_PREFIX + bdbs[i] + "\">Brown Driver Briggs</a>";
          renderings.push_back (rendering);
        }
      } else {
        id.clear ();
      }
      request->database_config_user ()->setRequestedMorphHbDefinition (id);
      
    } else if (letter == SBLGNT_PREFIX) {
      
      // SBL Greek New Testament plus morphology.
      if (id != request->database_config_user ()->getRequestedSblGntDefinition ()) {
        Database_MorphGnt database_morphgnt;
        Database_Strong database_strong;
        int rowid = convert_to_int (id.substr (1));
        // The part of speech.
        string pos = database_morphgnt.pos (rowid);
        string rendering = lexicon_logic_render_morphgnt_part_of_speech (pos);
        rendering.append (" ");
        // The parsing.
        string parsing = database_morphgnt.parsing (rowid);
        rendering.append (lexicon_logic_render_morphgnt_parsing_code (parsing));
        renderings.push_back (rendering);
        // The lemma.
        string lemma = database_morphgnt.lemma (rowid);
        vector <string> strongs = database_strong.strong (lemma);
        for (auto & id : strongs) {
          rendering = lexicon_logic_render_definition (id);
          if (!rendering.empty ()) renderings.push_back (rendering);
        }

      } else {
        id.clear ();
      }
      request->database_config_user ()->setRequestedSblGntDefinition (id);
      
    } else if (letter == "H") {
      
      // Strong's Hebrew.
      if (id != request->database_config_user ()->getRequestedHDefinition ()) {
        string rendering = lexicon_logic_render_definition (id);
        if (!rendering.empty ()) renderings.push_back (rendering);
      } else {
        id.clear ();
      }
      request->database_config_user ()->setRequestedHDefinition (id);
      
    } else if (letter == "G") {
      
      // Strong's Greek.
      if (id != request->database_config_user ()->getRequestedGDefinition ()) {
        string rendering = lexicon_logic_render_definition (id);
        if (!rendering.empty ()) renderings.push_back (rendering);
      } else {
        id.clear ();
      }
      request->database_config_user ()->setRequestedGDefinition (id);
      
    } else if (letter == BDB_PREFIX) {
      
      // Brown Driver Briggs lexicon.
      string rendering = lexicon_logic_render_bdb_entry (id.substr (1));
      if (!rendering.empty ()) renderings.push_back (rendering);
      request->database_config_user ()->setRequestedMorphHbDefinition ("");
      
    } else {

      // Unknown definition request.
      renderings.push_back (id);
      
    }
    
  }
  
  return filter_string_implode (renderings, "<br>");
}
Example #7
0
vector < Reference > search_in_bibledit()
// Advanced searching in Bibledit.
{
  // Configuration / session
  extern Settings *settings;
  // Set some variables in memory for higher speed.
  bool casesensitive = settings->session.search_case_sensitive;
  bool search_current_book = settings->session.search_current_book;
  bool search_current_chapter = settings->session.search_current_chapter;
  bool search_globbing = settings->session.search_globbing;
  bool search_start_word_match = settings->session.search_start_word_match;
  bool search_end_word_match = settings->session.search_end_word_match;
  set < unsigned int >selected_books = settings->session.selected_books;
  AreaType areatype = settings->session.area_type;
  bool area_id = settings->session.area_id;
  bool area_intro = settings->session.area_intro;
  bool area_heading = settings->session.area_heading;
  bool area_chapter = settings->session.area_chapter;
  bool area_study = settings->session.area_study;
  bool area_notes = settings->session.area_notes;
  bool area_xref = settings->session.area_xref;
  bool area_verse = settings->session.area_verse;

  // Progress information.
  ProgressWindow progresswindow(_("Searching"), true);

  // The string to search for. 
  // Note any apostrophies need to be doubled for SQLite.
  // We need to normalize the search expression when comparing strings.
  ustring localsearchword(settings->session.searchword.normalize());
  if (!casesensitive)
    localsearchword = localsearchword.casefold();
  ustring localsearchword2(localsearchword);

  // Storage for references: search results.
  vector < Reference > results;

  // Get our position in the text.
  ustring project = settings->genconfig.project_get();
  ustring book = books_id_to_english(settings->genconfig.book_get());
  unsigned int chapter = convert_to_int(settings->genconfig.chapter_get());

  // Go through each book in the project. Progress information.
  vector < unsigned int >availablebooks = project_get_books(project);
  progresswindow.set_iterate(0, 1, availablebooks.size());
  for (unsigned int bk = 0; bk < availablebooks.size(); bk++) {
    progresswindow.iterate();
    if (progresswindow.cancel) {
      return results;
    }
    // If the book is not to be searched, skip it.
    if (search_current_book)
      if (book != books_id_to_english(availablebooks[bk]))
        continue;
    if (selected_books.find(availablebooks[bk]) == selected_books.end())
      continue;

    try {
      // Go through each chapter in the book.
      vector < unsigned int >chapters = project_get_chapters(project, availablebooks[bk]);
      for (unsigned int ch = 0; ch < chapters.size(); ch++) {

        // Do we search this chapter?
        if (search_current_chapter)
          if (chapter != chapters[ch])
            continue;

        // Read the chapter.
        vector < ustring > lines = project_retrieve_chapter(project, availablebooks[bk], chapters[ch]);
        CategorizeChapterVerse ccv(lines);

        // Go through the verses.
        for (unsigned int i = 0; i < ccv.verse.size(); i++) {

          // Verse number.
          ustring verse = ccv.verse[i];

          // Handle casesensitive and area selection.
          // Assemble text to search through.
          ustring input(ccv.line[i]);
          if (!casesensitive)
            input = input.casefold();
          ustring text = search_in_bibledit_assemble_line(input, areatype, area_id, area_intro, area_heading, area_chapter, area_study, area_notes, area_xref, area_verse);

          // Use glob-style pattern matching or straight match.
          if (search_globbing) {
            ustring patternword = "*" + localsearchword + "*";
            if (!g_pattern_match_simple(patternword.c_str(), text.c_str()))
              continue;
          } else {
            if (text.find(localsearchword) == string::npos)
              continue;
          }

          // Do the word boundary matching.
          if (!search_in_bibledit_word_boundaries_match(text, localsearchword, search_start_word_match, search_end_word_match, search_globbing))
            continue;

          // This verse "passed" all tests: a search result.  
          Reference reference(availablebooks[bk], chapters[ch], verse);
          results.push_back(reference);
        }
      }
    }
    catch(exception & ex) {
      gw_critical(ex.what());
    }
  }

  // Give the results.
  return results;
}
Example #8
0
Stylesheet::Stylesheet(const ustring & name_in)
{
  gw_message("Creating Stylesheet called '" + name_in + "'");
  
  // Save the sheet's name.
  name = name_in;

  // If the name is empty, read from the template.
  ustring filename = stylesheet_xml_filename(name);
  if (name.empty())
    filename = stylesheet_xml_template_filename();

  // Read the xml data, bail out on failure.
  gchar *contents;
  g_file_get_contents(filename.c_str(), &contents, NULL, NULL);
  if (contents == NULL) {
    gw_critical(_("Failure reading stylesheet ") + filename);
		return;
  }

  // Parse the stylesheet.  
  xmlParserInputBufferPtr inputbuffer;
  inputbuffer = xmlParserInputBufferCreateMem(contents, strlen(contents), XML_CHAR_ENCODING_NONE);
  ustring value;
  xmlTextReaderPtr reader = xmlNewTextReader(inputbuffer, NULL);
  if (reader) {
    StyleV2 * style = NULL;
    while ((xmlTextReaderRead(reader) == 1)) {
      switch (xmlTextReaderNodeType(reader)) {
      case XML_READER_TYPE_ELEMENT:
	{
	  xmlChar *element_name = xmlTextReaderName(reader);
	  if (!xmlStrcmp(element_name, BAD_CAST "style")) {
	    char *attribute = (char *)xmlTextReaderGetAttribute(reader, BAD_CAST "marker");
	    if (attribute) {
	      style = new StyleV2 (0);
	      style->marker = attribute;
	      free(attribute);
	    }
	  }
	  free(element_name); element_name = NULL;
	  break;
	}
      case XML_READER_TYPE_TEXT:
	{
	  xmlChar *text = xmlTextReaderValue(reader);
	  if (text) {
	    value = (gchar *) text;
	    xmlFree(text);
	  }	
	  break;
	}
      case XML_READER_TYPE_END_ELEMENT:
	{
	  xmlChar *element_name = xmlTextReaderName(reader);
	  if (style) {
	    if (!xmlStrcmp(element_name, BAD_CAST "marker"))
	      style->marker = value;
	    if (!xmlStrcmp(element_name, BAD_CAST "name"))
	      style->name = value;
	    if (!xmlStrcmp(element_name, BAD_CAST "info"))
	      style->info = value;
	    if (!xmlStrcmp(element_name, BAD_CAST "type"))
	      style->type = (StyleType) convert_to_int(value);
	    if (!xmlStrcmp(element_name, BAD_CAST "subtype"))
	      style->subtype = convert_to_int(value);
	    if (!xmlStrcmp(element_name, BAD_CAST "fontsize"))
	      style->fontsize = convert_to_double(value);
	    if (!xmlStrcmp(element_name, BAD_CAST "italic"))
	      style->italic = value;
	    if (!xmlStrcmp(element_name, BAD_CAST "bold"))
	      style->bold = value;
	    if (!xmlStrcmp(element_name, BAD_CAST "underline"))
	      style->underline = value;
	    if (!xmlStrcmp(element_name, BAD_CAST "smallcaps"))
	      style->smallcaps = value;
	    if (!xmlStrcmp(element_name, BAD_CAST "superscript"))
	      style->superscript = convert_to_bool(value);
	    if (!xmlStrcmp(element_name, BAD_CAST "justification"))
	      style->justification = value;
	    if (!xmlStrcmp(element_name, BAD_CAST "spacebefore"))
	      style->spacebefore = convert_to_double(value);
	    if (!xmlStrcmp(element_name, BAD_CAST "spaceafter"))
	      style->spaceafter = convert_to_double(value);
	    if (!xmlStrcmp(element_name, BAD_CAST "leftmargin"))
	      style->leftmargin = convert_to_double(value);
	    if (!xmlStrcmp(element_name, BAD_CAST "rightmargin"))
	      style->rightmargin = convert_to_double(value);
	    if (!xmlStrcmp(element_name, BAD_CAST "firstlineindent"))
	      style->firstlineindent = convert_to_double(value);
	    if (!xmlStrcmp(element_name, BAD_CAST "spancolumns"))
	      style->spancolumns = convert_to_bool(value);
	    if (!xmlStrcmp(element_name, BAD_CAST "color"))
	      style->color = convert_to_int(value);
	    if (!xmlStrcmp(element_name, BAD_CAST "print"))
	      style->print = convert_to_bool(value);
	    if (!xmlStrcmp(element_name, BAD_CAST "userbool1"))
	      style->userbool1 = convert_to_bool(value);
	    if (!xmlStrcmp(element_name, BAD_CAST "userbool2"))
	      style->userbool2 = convert_to_bool(value);
	    if (!xmlStrcmp(element_name, BAD_CAST "userbool3"))
	      style->userbool3 = convert_to_bool(value);
	    if (!xmlStrcmp(element_name, BAD_CAST "userint1"))
	      style->userint1 = convert_to_int(value);
	    if (!xmlStrcmp(element_name, BAD_CAST "userint2"))
	      style->userint2 = convert_to_int(value);
	    if (!xmlStrcmp(element_name, BAD_CAST "userint3"))
	      style->userint3 = convert_to_int(value);
	    if (!xmlStrcmp(element_name, BAD_CAST "userstring1"))
	      style->userstring1 = value;
	    if (!xmlStrcmp(element_name, BAD_CAST "userstring2"))
	      style->userstring2 = value;
	    if (!xmlStrcmp(element_name, BAD_CAST "userstring3"))
	      style->userstring3 = value;
	  }
	  value.clear();
	  if (!xmlStrcmp(element_name, BAD_CAST "style")) {
	    if (style) {
	      insert (style);
	      style = NULL;
	    }
	  }
	  free(element_name); element_name = NULL;
	  break;
	}
      }
    }
  }

  // Free memory.
	if (reader)
		xmlFreeTextReader(reader);
	if (inputbuffer)
		xmlFreeParserInputBuffer(inputbuffer);
	if (contents)
		g_free(contents);
}
Example #9
0
string resource_logic_get_html (void * webserver_request,
                                string resource, int book, int chapter, int verse,
                                bool add_verse_numbers)
{
  Webserver_Request * request = (Webserver_Request *) webserver_request;

  string html;
  
  Database_UsfmResources database_usfmresources;
  Database_ImageResources database_imageresources;
  Database_Mappings database_mappings;
  
  // Lists of the various types of resources.
  vector <string> bibles = request->database_bibles()->getBibles ();
  vector <string> usfms;
  if (config_logic_client_prepared ()) {
    usfms = client_logic_usfm_resources_get ();
    // As from February 2016 a client no longer automatically downloads USFM resources off the server.
    // But a client takes in account existing USFM resources it has downloaded before.
    vector <string> old_usfms = database_usfmresources.getResources ();
    usfms.insert (usfms.end (), old_usfms.begin (), old_usfms.end ());
  } else {
    usfms = database_usfmresources.getResources ();
  }
  vector <string> externals = resource_external_names ();
  vector <string> images = database_imageresources.names ();
  vector <string> lexicons = lexicon_logic_resource_names ();

  // Possible SWORD details.
  string sword_module = sword_logic_get_remote_module (resource);
  string sword_source = sword_logic_get_source (resource);
  
  // Determine the type of the current resource.
  bool isBible = in_array (resource, bibles);
  bool isUsfm = in_array (resource, usfms);
  bool isExternal = in_array (resource, externals);
  bool isImage = in_array (resource, images);
  bool isLexicon = in_array (resource, lexicons);
  bool isSword = (!sword_source.empty () && !sword_module.empty ());

  // Retrieve versification system of the active Bible.
  string bible = request->database_config_user ()->getBible ();
  string bible_versification = Database_Config_Bible::getVersificationSystem (bible);

  // Determine the versification system of the current resource.
  string resource_versification;
  if (isBible || isUsfm) {
    resource_versification = Database_Config_Bible::getVersificationSystem (bible);
  } else if (isExternal) {
    resource_versification = resource_external_mapping (resource);
  } else if (isImage) {
  } else if (isLexicon) {
    resource_versification = database_mappings.original ();
    if (resource == KJV_LEXICON_NAME) resource_versification = "English";
  } else if (isSword) {
    resource_versification = "English";
  } else {
  }

  // If the resource versification system differs from the Bible's versification system,
  // map the focused verse of the Bible to a verse in the Resource.
  // There are resources without versification system: Do nothing about them.
  vector <Passage> passages;
  if ((bible_versification != resource_versification) && !resource_versification.empty ()) {
    passages = database_mappings.translate (bible_versification, resource_versification, book, chapter, verse);
  } else {
    passages.push_back (Passage ("", book, chapter, convert_to_string (verse)));
  }

  // If there's been a mapping, the resource should include the verse number for clarity.
  if (passages.size () != 1) add_verse_numbers = true;
  for (auto passage : passages) {
    if (verse != convert_to_int (passage.verse)) {
      add_verse_numbers = true;
    }
  }
  
  for (auto passage : passages) {
    
    int book = passage.book;
    int chapter = passage.chapter;
    int verse = convert_to_int (passage.verse);
    
    string possible_included_verse;
    if (add_verse_numbers) possible_included_verse = convert_to_string (verse) + " ";
    if (isImage) possible_included_verse.clear ();
    
    html.append (resource_logic_get_verse (webserver_request, resource, book, chapter, verse));
  }
  
  return html;
}
Example #10
0
void kjv_get_strongs_data (const Reference& reference, vector <ustring>& strongs, vector <ustring>& words)
// This gets the words and their applicable Strong's numbers for a verse.
{
  sqlite3 *db;
  int rc;
  char *error = NULL;
  try {
    // Open the database.
    rc = sqlite3_open(kjv_sql_filename().c_str(), &db);
    if (rc)
      throw runtime_error(sqlite3_errmsg(db));
    sqlite3_busy_timeout(db, 1000);
    // Retrieve the bits.
    SqliteReader reader(0);
    char *sql;
    sql = g_strdup_printf("select fragment, lemma from kjv where book = %d and chapter = %d and verse = %d order by item asc;", reference.book_get(), reference.chapter_get(), convert_to_int (reference.verse_get()));
    rc = sqlite3_exec(db, sql, reader.callback, &reader, &error);
    g_free(sql);
    if (rc) {
      throw runtime_error(sqlite3_errmsg(db));
    }
    words = reader.ustring0;
    strongs = reader.ustring1;
  }
  catch(exception & ex) {
    gw_critical(ex.what());
  }
  sqlite3_close(db);
}
Example #11
0
string resource_img (void * webserver_request)
{
  Webserver_Request * request = (Webserver_Request *) webserver_request;
  Database_ImageResources database_imageresources;

  
  string page;
  Assets_Header header = Assets_Header (translate("Image resources"), request);
  page = header.run ();
  Assets_View view;
  string error, success;
  int book1, chapter1, verse1, book2, chapter2, verse2;
  
  
  string name = request->query ["name"];
  view.set_variable ("name", name);

  
  string image = request->query ["image"];
  view.set_variable ("image", image);

  
  int userid = filter_string_user_identifier (webserver_request);

  
  if (request->post.count ("submit")) {
    
    vector <string> errors;
    
    string book = request->post ["book1"];
    book1 = filter_passage_interpret_book (book);
    if (book1 == 0) errors.push_back (translate ("Unknown starting book."));

    chapter1 = convert_to_int (request->post ["chapter1"]);
    if (chapter1 < 0) errors.push_back (translate ("Negative starting chapter."));
    if (chapter1 > 200) errors.push_back (translate ("High starting chapter."));
    
    verse1 = convert_to_int (request->post ["verse1"]);
    if (chapter1 < 0) errors.push_back (translate ("Negative starting verse."));
    if (chapter1 > 200) errors.push_back (translate ("High starting verse."));
    
    book = request->post ["book2"];
    book2 = filter_passage_interpret_book (book);
    if (book2 == 0) errors.push_back (translate ("Unknown ending book."));
    
    chapter2 = convert_to_int (request->post ["chapter2"]);
    if (chapter2 < 0) errors.push_back (translate ("Negative ending chapter."));
    if (chapter2 > 200) errors.push_back (translate ("High ending chapter."));
    
    verse2 = convert_to_int (request->post ["verse2"]);
    if (chapter2 < 0) errors.push_back (translate ("Negative ending verse."));
    if (chapter2 > 200) errors.push_back (translate ("High ending verse."));
    
    int start = filter_passage_to_integer (Passage ("", book1, chapter1, convert_to_string (verse1)));
    int end = filter_passage_to_integer (Passage ("", book2, chapter2, convert_to_string (verse2)));
    if (start > end) {
      errors.push_back (translate ("The starting passage is beyond the ending passage."));
    }

    database_imageresources.assign (name, image, book1, chapter1, verse1, book2, chapter2, verse2);
    
    Database_Volatile::setValue (userid, "imageresources", convert_to_string (end));

    error = filter_string_implode (errors, " ");
    if (errors.empty ()) {
      redirect_browser (request, filter_url_build_http_query (resource_image_url (), "name", name));
      return "";
    }
  }
  
  
  // Retrieve passage range for this image.
  database_imageresources.get (name, image, book1, chapter1, verse1, book2, chapter2, verse2);
  if ((book1 == 0) || (book2 == 0)) {
    string end = Database_Volatile::getValue (userid, "imageresources");
    Passage passage = filter_integer_to_passage (convert_to_int (end));
    book1 = book2 = passage.book;
    chapter1 = chapter2 = passage.chapter;
    verse1 = verse2 = convert_to_int (passage.verse);
    if (book1 == 0) book1 = 1;
    if (book2 == 0) book2 = 1;
  }
  view.set_variable ("book1", Database_Books::getEnglishFromId (book1));
  view.set_variable ("chapter1", convert_to_string (chapter1));
  view.set_variable ("verse1", convert_to_string (verse1));
  view.set_variable ("book2", Database_Books::getEnglishFromId (book2));
  view.set_variable ("chapter2", convert_to_string (chapter2));
  view.set_variable ("verse2", convert_to_string (verse2));
  

  view.set_variable ("success", success);
  view.set_variable ("error", error);
  page += view.render ("resource", "img");
  page += Assets_Page::footer ();
  return page;
}
Example #12
0
void kjv_import_sword (const ustring& textfile, const ustring& database)
{
  // Show the progress. KJV has 31102 verses.
  ProgressWindow progresswindow (_("Importing King James Bible"), false);
  progresswindow.set_iterate (0, 1, 31102);
  gchar * contents;
  g_file_get_contents(textfile.c_str(), &contents, NULL, NULL);
  if (!contents)
    return;

  // Create the database, put it in fast mode.
  unix_unlink (database.c_str());
  sqlite3 *db;
  sqlite3_open(database.c_str(), &db);
  sqlite3_exec(db, "create table kjv (book integer, chapter integer, verse integer, item integer, fragment text, lemma text);", NULL, NULL, NULL);
  sqlite3_exec(db, "PRAGMA synchronous=OFF;", NULL, NULL, NULL);

  // Parse input.
  xmlParserInputBufferPtr inputbuffer;
  inputbuffer = xmlParserInputBufferCreateMem(contents, strlen (contents), XML_CHAR_ENCODING_NONE);
  xmlTextReaderPtr reader = xmlNewTextReader(inputbuffer, NULL);
  if (reader) {
    bool within_relevant_element = false;
    Reference reference (0, 0, "0");
    unsigned int item_number = 0;
    ustring textfragment;
    ustring lemmata;
    while ((xmlTextReaderRead(reader) == 1)) {
      switch (xmlTextReaderNodeType(reader)) {
      case XML_READER_TYPE_ELEMENT:
        {
          xmlChar *element_name = xmlTextReaderName(reader);
          // Deal with a verse element.
          if (!xmlStrcmp(element_name, BAD_CAST "verse")) {
            progresswindow.iterate();
            char *attribute;
            attribute = (char *)xmlTextReaderGetAttribute(reader, BAD_CAST "osisID");
            if (attribute) {
              Parse parse (attribute, false, ".");
              if (parse.words.size() == 3) {
                reference.assign(books_osis_to_id (parse.words[0]), // book
				 convert_to_int (parse.words[1]),   // chapter
				 parse.words[2]);                   // verse
              } else {
                gw_critical (attribute);
              }
              free(attribute);
            }
            item_number = 0;
          }
          // Deal with a w element.
          if (!xmlStrcmp(element_name, BAD_CAST "w")) {
            within_relevant_element = true;
            item_number++;
            textfragment.clear();
            lemmata.clear();
            char *attribute;
            attribute = (char *)xmlTextReaderGetAttribute(reader, BAD_CAST "lemma");
            if (attribute) {
              lemmata = attribute;
              free(attribute);
            }
          }
          break;
        }
      case XML_READER_TYPE_TEXT:
        {
          if (within_relevant_element) {
            xmlChar *text = xmlTextReaderValue(reader);
            if (text) {
              textfragment = (const char *)text;
              xmlFree(text);
              textfragment = textfragment.casefold();
            }
          }
          break;
        }
      case XML_READER_TYPE_END_ELEMENT:
        {
          xmlChar *element_name = xmlTextReaderName(reader);
          if (!xmlStrcmp(element_name, BAD_CAST "w")) {
            replace_text (lemmata, "strong:", "");
            char *sql;
            sql = g_strdup_printf("insert into kjv values (%d, %d, %d, %d, '%s', '%s');", 
                                  reference.book_get(), reference.chapter_get(), convert_to_int (reference.verse_get()), 
                                  item_number, 
                                  double_apostrophy (textfragment).c_str(), lemmata.c_str());
            sqlite3_exec(db, sql, NULL, NULL, NULL);
            g_free(sql);
            within_relevant_element = false;
          }
          break;
        }
      }
    }
  }
  if (reader)
    xmlFreeTextReader(reader);
  if (inputbuffer)
    xmlFreeParserInputBuffer(inputbuffer);

  // Close database.
  sqlite3_close(db);
  
  // Free xml data.    
  g_free(contents);
}
Example #13
0
int Database_Config_Bible::getIValue (string bible, const char * key, int default_value)
{
  return convert_to_int (getValue (bible, key, convert_to_string (default_value).c_str()));
}
Example #14
0
void webserver ()
{
  // Setup server behaviour.
  config_globals_client_prepared = config_logic_client_prepared ();
  if (strcmp (DEMO, "yes") == 0) config_globals_open_installation = true;

  // Create a listening socket.
  int listenfd = socket(AF_INET, SOCK_STREAM, 0);
  if (listenfd < 0) cerr << "Error opening socket: It returns a descriptor of " << listenfd << endl;

  // Eliminate "Address already in use" error from bind.
  int optval = 1;
  int result = setsockopt (listenfd, SOL_SOCKET, SO_REUSEADDR, (const char *) &optval, sizeof (int));
  if (result != 0) cerr << "Error setting socket options" << endl;

  // The listening socket will be an endpoint for all requests to a port on any IP address for this host.
  typedef struct sockaddr SA;
  struct sockaddr_in serveraddr;
  memset (&serveraddr, 0, sizeof (serveraddr));
  serveraddr.sin_family = AF_INET;
  serveraddr.sin_addr.s_addr = htonl (INADDR_ANY);
  serveraddr.sin_port = htons (convert_to_int (config_logic_network_port ()));
  result = mybind (listenfd, (SA *) &serveraddr, sizeof (serveraddr));
  if (result != 0) cerr << "Error binding server to socket" << endl;

  // Make it a listening socket ready to accept many connection requests.
  result = listen (listenfd, 100);
  if (result != 0) cerr << "Error listening on socket" << endl;

  // Ignore SIGPIPE signal: When the browser cancels the request, it won't kill Bibledit.
  signal (SIGPIPE, SIG_IGN);

  // Keep waiting for, accepting, and processing connections.
  config_globals_running = true;
  while (config_globals_running) {

    // Socket and file descriptor for the client connection.
    struct sockaddr_in clientaddr;
    socklen_t clientlen = sizeof(clientaddr);
    int connfd = accept (listenfd, (SA *)&clientaddr, &clientlen);
    if (connfd > 0) {

      // Socket receive timeout.
      struct timeval tv;
      tv.tv_sec = 60;
      tv.tv_usec = 0;
      setsockopt (connfd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
      
      // The client's remote IPv4 address in dotted notation.
      char remote_address[256];
      inet_ntop (AF_INET, &clientaddr.sin_addr.s_addr, remote_address, sizeof (remote_address));
      string clientaddress = remote_address;
      
      // Handle this request in a thread, enabling parallel requests.
      thread request_thread = thread (webserver_process_request, connfd, clientaddress);
      // Detach and delete thread object.
      request_thread.detach ();
      
    } else {
      cerr << "Error accepting connection on socket" << endl;
    }
  }
  
  // Close listening socket, freeing it for a possible subsequent server process.
  close (listenfd);
}
Example #15
0
void COM_interface::process_speed_change() {
	unsigned int	baud;
#ifdef LINUX
	speed_t		selectedBaud = B9600;
#endif
	baud = convert_to_int(3);

	//delay(5);
#ifndef LINUX
	fSuccess = GetCommState(hCom, &dcb);
	if(!fSuccess) {
#ifndef _DLL_VERSION
		cout << "Could not change speed" << endl;
#endif
		throw runtime_error("Could not change speed!");
	}
#endif
	if((baud > 110000) && (baud < 120000)) {
#ifndef LINUX
		dcb.BaudRate = 115200;
#else
		selectedBaud = B115200;
#endif
	}

	if((baud > 50000) && (baud < 60000)) {
#ifndef LINUX
		dcb.BaudRate = 57600;
#else
		selectedBaud = B57600;
#endif
	}

	if((baud > 30000) && (baud < 40000)) {
#ifndef LINUX
		dcb.BaudRate = 38400;
#else
		selectedBaud = B38400;
#endif
	}

	if((baud > 15000) && (baud < 25000)) {
#ifndef LINUX
		dcb.BaudRate = 19200;
#else
		selectedBaud = B19200;
#endif
	}

	if((baud > 8000) && (baud < 12000)) {
#ifndef LINUX
		dcb.BaudRate = 9600;
#else
		selectedBaud = B9600;
#endif
	}

#ifndef LINUX
	current_speed = dcb.BaudRate;
#else
	current_speed = selectedBaud;
#endif

	delay(speed_delay);
#ifndef LINUX
	fSuccess = SetCommState(hCom, &dcb);
#else
	fSuccess = false;
	cfsetospeed(&termSetParam, selectedBaud);
	cfsetispeed(&termSetParam, selectedBaud);

	if( tcsetattr(hCom, TCSAFLUSH, &termSetParam) != -1 )
		fSuccess = true;
#endif
	if(fSuccess == false) {
#ifndef _DLL_VERSION
		cout << "Error changing speed - trying to restore communication..." << endl;
#endif
		//throw runtime_error("Error changing speed!");
		got_error_speed_change = true;
		delay(3);
		return;
	}
	send_message(r_polling, 4, "Polling");
	if(get_message(20) == false) {
#ifndef _DLL_VERSION
		cout << "Can't change the speed - trying to restore communication..." << endl;
#endif
		//throw runtime_error("Can't change the speed!");
		got_error_speed_change = true;
		delay(3);
		return;
	} else
		got_speed_change = true;
	send_message(r_polling, 4, "Polling");
	get_message(2);	// ack
	send_message(r_polling, 4, "Polling");
	get_message(1);	// ack
	cout<<"Speed change OK"<<endl;
}
Example #16
0
string editusfm_save (void * webserver_request)
{
    Webserver_Request * request = (Webserver_Request *) webserver_request;


    string bible = request->post["bible"];
    int book = convert_to_int (request->post["book"]);
    int chapter = convert_to_int (request->post["chapter"]);
    string usfm = request->post["usfm"];
    string checksum = request->post["checksum"];


    if (request->post.count ("bible") && request->post.count ("book") && request->post.count ("chapter") && request->post.count ("usfm")) {
        if (Checksum_Logic::get (usfm) == checksum) {
            usfm = filter_url_tag_to_plus (usfm);
            usfm = filter_string_trim (usfm);
            if (usfm != "") {
                if (unicode_string_is_valid (usfm)) {
                    string stylesheet = request->database_config_user()->getStylesheet();
                    vector <BookChapterData> book_chapter_text = usfm_import (usfm, stylesheet);
                    for (BookChapterData & data : book_chapter_text) {
                        int book_number = data.book;
                        int chapter_number = data.chapter;
                        string chapter_data_to_save = data.data;
                        if (((book_number == book) || (book_number == 0)) && (chapter_number == chapter)) {
                            string ancestor_usfm = getLoadedUsfm (webserver_request, bible, book, chapter, "editusfm");
                            // Collect some data about the changes for this user.
                            string username = request->session_logic()->currentUser ();
                            int oldID = request->database_bibles()->getChapterId (bible, book, chapter);
                            string oldText = ancestor_usfm;
                            string newText = chapter_data_to_save;
                            // Merge if the ancestor is there and differs from what's in the database.
                            if (!ancestor_usfm.empty ()) {
                                string server_usfm = request->database_bibles ()->getChapter (bible, book, chapter);
                                if (server_usfm != ancestor_usfm) {
                                    // Prioritize the USFM to save.
                                    chapter_data_to_save = filter_merge_run (ancestor_usfm, server_usfm, chapter_data_to_save);
                                    Database_Logs::log (translate ("Merging and saving chapter."));
                                }
                            }
                            // Check on write access.
                            if (access_bible_book_write (request, "", bible, book)) {
                                // Safely store the chapter.
                                string message = usfm_safely_store_chapter (request, bible, book, chapter, chapter_data_to_save);
                                if (message.empty()) {
#ifndef CLIENT_PREPARED
                                    // Server configuration: Store details for the user's changes.
                                    int newID = request->database_bibles()->getChapterId (bible, book, chapter);
                                    Database_Modifications database_modifications;
                                    database_modifications.recordUserSave (username, bible, book, chapter, oldID, oldText, newID, newText);
                                    Database_Git::store_chapter (username, bible, book, chapter, oldText, newText);
#endif
                                    // Store a copy of the USFM loaded in the editor for later reference.
                                    storeLoadedUsfm (webserver_request, bible, book, chapter, "editusfm");
                                    return locale_logic_text_saved ();
                                }
                                return message;
                            } else {
                                return translate("No write access");
                            }
                        } else {
                            Database_Logs::log ("The following data could not be saved and was discarded: " + chapter_data_to_save);
                            return translate("Passage mismatch");
                        }
                    }
                } else {
                    Database_Logs::log ("The text was not valid Unicode UTF-8. The chapter could not saved and has been reverted to the last good version.");
                    return translate("Needs Unicode");
                }
            } else {
                Database_Logs::log ("There was no text. Nothing was saved. The original text of the chapter was reloaded.");
                return translate("Nothing to save");
            }
        } else {
            request->response_code = 409;
            return translate("Checksum error");
        }
    } else {
        return translate("Nothing to save");
    }
    return translate ("Confusing data");
}
Example #17
0
unsigned int RevertDialog::chapter_get()
{
  ustring uchapter = combobox_get_active_string(comboboxchapter);
  unsigned int chapter = convert_to_int(uchapter);
  return chapter;
}
Example #18
0
string checks_index (void * webserver_request)
{
  Webserver_Request * request = (Webserver_Request *) webserver_request;
  Database_Check database_check;

  
  string page;
  Assets_Header header = Assets_Header (translate("Checks"), webserver_request);
  header.addBreadCrumb (menu_logic_tools_menu (), menu_logic_tools_text ());
  page = header.run ();
  Assets_View view;
  

  if (request->query.count ("approve")) {
    int approve = convert_to_int (request->query["approve"]);
    database_check.approve (approve);
    view.set_variable ("success", translate("The entry was suppressed."));
  }
  
                        
  if (request->query.count ("delete")) {
    int erase = convert_to_int (request->query["delete"]);
    database_check.erase (erase);
    view.set_variable ("success", translate("The entry was deleted for just now."));
  }

  
  // Get the Bibles the user has write-access to.
  vector <int> bibleIDs;
  vector <string> bibles = request->database_bibles()->getBibles ();
  for (auto bible : bibles) {
    if (access_bible_write (webserver_request, bible)) {
      int id = request->database_bibles()->getID (bible);
      bibleIDs.push_back (id);
    }
  }
  
  
  string resultblock;
  vector <Database_Check_Hit> hits = database_check.getHits ();
  for (auto hit : hits) {
    int bibleID = hit.bible;
    if (find (bibleIDs.begin(), bibleIDs.end (), bibleID) != bibleIDs.end ()) {
      int id = hit.rowid;
      string bible = filter_string_sanitize_html (request->database_bibles()->getName (bibleID));
      int book = hit.book;
      int chapter = hit.chapter;
      int verse = hit.verse;
      string link = filter_passage_link_for_opening_editor_at (book, chapter, convert_to_string (verse));
      string information = filter_string_sanitize_html (hit.data);
      resultblock.append ("<p>\n");
      resultblock.append ("<a href=\"index?approve=" + convert_to_string (id) + "\"> ✔ </a>\n");
      resultblock.append ("<a href=\"index?delete=" + convert_to_string (id) + "\"> ✗ </a>\n");
      resultblock.append (bible);
      resultblock.append (" ");
      resultblock.append (link);
      resultblock.append (" ");
      resultblock.append (information);
      resultblock.append ("</p>\n");
    }
  }
  view.set_variable ("resultblock", resultblock);


  page += view.render ("checks", "index");
  page += Assets_Page::footer ();
  return page;
}
Example #19
0
uint64_t tarfs_init(char *binname,process* p){
	int i=0,j=0,fsize,diff; 
	volatile char sizestr[12];
	Elf64_Ehdr* elfhdr;
	Elf64_Phdr* pchdr;

	volatile char* srcptr;
	volatile char* destptr;
	uint64_t ret_addr=0;
	volatile void* file = (void*)( &(_binary_tarfs_start) );
	tarfs* filehdr = (tarfs *)file;


	while(1){
		//print("j=%d File size = %s .....File Name= %s ~~ ~~ ",j,filehdr->size,filehdr->name);


		for (i=0;i<12;i++){
			*(sizestr+i) = *((filehdr->size) + i);
		}
		fsize=convert_to_int(sizestr);


		if ((fsize !=0)&& (strcmp(binname,filehdr->name)==0)){
			elfhdr=(Elf64_Ehdr *)(file + sizeof(tarfs));  
			ret_addr=(elfhdr->e_entry);
			for(i=0;i<elfhdr->e_phnum;i++){
				pchdr =(Elf64_Phdr *)(file + sizeof(tarfs) + (elfhdr->e_phoff) + i*(elfhdr->e_phentsize) );   

				if(pchdr->p_filesz ==0 && pchdr->p_memsz == 0){
					continue;
				}

				destptr=(char *)(pchdr->p_vaddr);                      //destination pointer
				srcptr=(char *) (file + sizeof(tarfs) + pchdr->p_offset );  //source pointer
				//uint64_t start_address = (uint64_t)destptr;
				//uint64_t end_address = start_address + pchdr->p_filesz;
				//uint64_t size = pchdr->p_filesz;
				allocate_VMA_memory((uint64_t)srcptr,(uint64_t)destptr,pchdr->p_filesz,pchdr->p_memsz,2,p);
				//print("src ptr %x and dest ptr = %x and fsize = %x",srcptr,destptr,size);
				//create_empty_page((uint64_t)srcptr,p);	
				//create_empty_page((uint64_t)destptr,p->reg.cr3);	
				//create_empty_page((uint64_t)destptr,p);	
				//memcpy(srcptr,destptr,(pchdr->p_filesz));
			}  
			p->start_exec = ret_addr; 
			break;

		}   

		diff = 512- ((sizeof(tarfs) + fsize) % 512);
		////print(";diff=%d ;",diff);
		if (diff==512)
			diff=0;
		file += sizeof(tarfs) + fsize + diff;

		if (file-(void *)&(_binary_tarfs_end) >=0){
			//print("\n Tarfs range exceeded!");
			break;
		}    
		else 
			filehdr=(tarfs *)(file);

		j++;
	}	
	//print(" ret_addr=%x ;", ret_addr);
	return  ret_addr;
}
Example #20
0
void FindNoteDialog::on_buttonfind_clicked()
{
  extern Settings *settings;

  // Connect to database.
  sqlite3 *db;
  int rc;
  char *error = NULL;
  try {
    rc = sqlite3_open(notes_index_filename().c_str(), &db);
    if (rc)
      throw runtime_error(sqlite3_errmsg(db));
    sqlite3_busy_timeout(db, 1000);

    // Get the word to search for.
    settings->session.searchword = gtk_entry_get_text(GTK_ENTRY(entry1));
    settings->session.search_case_sensitive = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(checkbutton_case));

    // Get the string to search for.
    // We need to normalize the search expression, as prescribed, when comparing strings.
    ustring searchword_verbatim = settings->session.searchword.normalize();
    ustring searchword_casefold = searchword_verbatim.casefold();

    // Go through the whole index database.
    SqliteReader reader(0);
    char *sql;
    sql = g_strdup_printf(_("select id, casefolded from notes;"));
    rc = sqlite3_exec(db, sql, reader.callback, &reader, &error);
    g_free(sql);
    if (rc != SQLITE_OK) {
      throw runtime_error(error);
    }
    for (unsigned int i = 0; i < reader.ustring0.size(); i++) {

      // See whether the case-insensitive word to search for is in this note.
      ustring casefolded_note = reader.ustring1[i];
      if (casefolded_note.find(searchword_casefold) != string::npos) {

        // Read the note from disk.
        gint32 id = convert_to_int(reader.ustring0[i]);
        ustring note;
        ustring project;
        ustring fullreference;
        ustring category;
        int date_created;
        ustring user_created;
        int date_modified;
        ustring logbook;
        notes_read_one_from_file (id, note, project, fullreference, category, date_created, user_created, date_modified, logbook);

        // If case sensitive search, do an additional test.
        if (settings->session.search_case_sensitive) {
          if (note.find (searchword_verbatim) == string::npos) {
            continue;
          }
        }

        // Get the numerical equivalent of the reference.
        ustring reference = fullreference;
        {
          // Parse the string into its possible several references.
          Parse parse(reference);
          // Take the first refence available.
          if (parse.words.size() > 0)
            reference = parse.words[0];
        }

        // Store data.
        ids.push_back(id);
        references.push_back(reference);
        allreferences.push_back(fullreference);
        dates.push_back(date_modified);
      }
    }

    // Sort the notes.
    notes_sort(ids, references, allreferences, dates);
  }
  catch(exception & ex) {
    gw_critical(ex.what());
  }

  // Close connection.  
  sqlite3_close(db);

  // Entry completion
  completion_finish(entry1, cpSearch);
}
Example #21
0
// spacetimescaling <init_path> [-i <init_template> <init_length>] [-o <final_path>] <final_template> <final_width> <final_height> <final_length> <scaling_method>
int main(int argc, char *argv[])
{
    char *spath, *init_template = NULL, *final_path, *final_template, *scaling_method;
    // Wczytywanie danych wejsciowych
    int i = 2;
    if(!argv[1])
        return 1;
    if(!strcmp(argv[2], "-i"))
    {
        if(!(init_template = argv[3]) || !(init_length = convert_to_int(argv[4])) || !check_tmplt(init_template, argv[4]))
            return 1;
        i = 5;
    }
    final_path = spath = malloc(strlen(argv[1]) + 2);
    strcpy(spath, argv[1]);
    if(*(argv[1] + strlen(argv[1]) - 1) != '/')
    {
        #ifdef _WIN32
            if(*(argv[1] + strlen(argv[1]) - 1) != '\\')
                strcat(spath, "/");
        #else
            strcat(spath, "/");
        #endif // _WIN32
    }
    if(!strcmp(argv[i], "-o"))
    {
        if(!argv[i + 1])
        {
            free(spath);
            return 1;
        }
        final_path = malloc(strlen(argv[i + 1]) + 2);
        strcpy(final_path, argv[i + 1]);
        if(*(argv[i + 1] + strlen(argv[i + 1]) - 1) != '/')
        {
            #ifdef _WIN32
                if(*(argv[i + 1] + strlen(argv[i + 1]) - 1) != '\\')
                    strcat(final_path, "/");
            #else
                strcat(final_path, "/");
            #endif // _WIN32
        }
        i+=2;
    }
    if(!(final_template = argv[i]) || !(final_width = convert_to_int(argv[i + 1])) || !(final_height = convert_to_int(argv[i + 2])) || !(final_length = convert_to_int(argv[i + 3])) || !check_tmplt(final_template, argv[i + 3]) || !(scaling_method = argv[i + 4]) || (strcmp(scaling_method, "NEIGHBOR") && strcmp(scaling_method, "LINEAR") && strcmp(scaling_method, "BICUBIC")) || argv[i + 5])
    {
        if(final_path != spath)
            free(final_path);
        free(spath);
        dispose();
        return 1;
    }
    if(!imgread(spath, init_template) || (!strcmp(scaling_method, "LINEAR") && init_width < 2) || (!strcmp(scaling_method, "BICUBIC") && (init_width < 3 || init_height < 3)))
    {
        if(final_path != spath)
            free(final_path);
        free(spath);
        dispose();
        return 2;
    }
    interpolate(scaling_method);
    if(!imgwrite(final_path, final_template))
    {
        if(final_path != spath)
            free(final_path);
        free(spath);
        dispose();
        return 3;
    }
    if(final_path != spath)
            free(final_path);
    free(spath);
    dispose();
    return 0;
}
Example #22
0
void notes_select(vector <unsigned int>& ids, unsigned int & id_cursor, const ustring& currentreference,
                   const ustring& category, NotesSelectionReferenceType refselection, NotesSelectionEditedType editedselection,
                   bool currentprojectselection, int date_from, int date_to) 
/*
 This selects notes for display.
 It does this based on the variables passed, including the current reference.
 The resulting selection will be stored in ids.
 It gives "id_cursor" which contains the id the cursor has to be put at.
 */
{
  // Clear ids.
  ids.clear();
  // The average numerical equivalent of current reference.
  int numerical_currentreference = 0;
  {
    ustring book, chapter, verse;
    decode_reference(currentreference, book, chapter, verse);
    vector <int>verses = verses_encode(verse);
    for (unsigned int i = 0; i < verses.size(); i++) {
      numerical_currentreference += verses[i];
    }
    if (!verses.empty())
      numerical_currentreference /= verses.size();
    numerical_currentreference += reference_to_numerical_equivalent(book, chapter, "0");
  }
  // Date selection.
  int currentdate = date_time_julian_day_get_current();
  // Cursor focus calculation.
  int minimum_cursor_distance = G_MAXINT;
  // Database variables.
  sqlite3 *db;
  int rc;
  char *error = NULL;
  try {
    // Connect to database.
    rc = sqlite3_open(notes_index_filename().c_str(), &db);
    if (rc) throw runtime_error(sqlite3_errmsg(db));
    sqlite3_busy_timeout(db, 1000);
    SqliteReader sqlitereader(0);
    // See which notes to select.
    switch (refselection) {
      case nsrtCurrentVerse:
      {
        // This selects any notes which refer to the current verse.
        ustring book, chapter, verse;
        decode_reference(currentreference, book, chapter, verse);
        unsigned int verse_zero;
        verse_zero = reference_to_numerical_equivalent(book, chapter, "0");
        vector < int >verses = verses_encode(verse);
        for (unsigned int i = 0; i < verses.size(); i++) {
          ustring this_verse = convert_to_string(int (verse_zero + verses[i]));
          char *sql;
          sql = g_strdup_printf("select id, reference, modified, project, category from notes where reference glob ('* %s *');", this_verse.c_str());
          rc = sqlite3_exec(db, sql, sqlitereader.callback, &sqlitereader, &error);
          g_free(sql);
          if (rc != SQLITE_OK) {
            throw runtime_error(error);
          }
        }
        break;
      }
      case nsrtCurrentChapter:
      {
        // This selects any notes which refer to the current chapter.
        ustring book, chapter, verse;
        decode_reference(currentreference, book, chapter, verse);
        unsigned int verse_zero;
        verse_zero = reference_to_numerical_equivalent(book, chapter, "0");
        ustring this_chapter = convert_to_string(verse_zero);
        this_chapter.erase(this_chapter.length() - 3, 3);
        char *sql;
        sql = g_strdup_printf("select id, reference, modified, project, category from notes where reference glob ('* %s??? *');", this_chapter.c_str());
        rc = sqlite3_exec(db, sql, sqlitereader.callback, &sqlitereader, &error);
        g_free(sql);
        if (rc != SQLITE_OK) {
          throw runtime_error(error);
        }
        break;
      }
      case nsrtCurrentBook:
      {
        // This selects any notes which refer to the current book.
        ustring book, chapter, verse;
        decode_reference(currentreference, book, chapter, verse);
        unsigned int verse_zero;
        verse_zero = reference_to_numerical_equivalent(book, chapter, "0");
        ustring this_book = convert_to_string(verse_zero);
        this_book.erase(this_book.length() - 6);
        char *sql;
        sql = g_strdup_printf("select id, reference, modified, project, category from notes where reference glob ('* %s?????? *');", this_book.c_str());
        rc = sqlite3_exec(db, sql, sqlitereader.callback, &sqlitereader, &error);
        g_free(sql);
        if (rc != SQLITE_OK) {
          throw runtime_error(error);
        }
        break;
      }
      case nsrtAny:
      {
        rc = sqlite3_exec(db, "select id, reference, modified, project, category from notes;", sqlitereader.callback, &sqlitereader, &error);
        if (rc != SQLITE_OK) {
          throw runtime_error(error);
        }
        break;
      }
    }
    // Storage for sorting purposes.
    vector <ustring> references;
    vector <int> distances;
    set <gint32> already_stored_ids;
    // Read all resulting data from the database. Make further selections.
    for (unsigned int rc = 0; rc < sqlitereader.ustring0.size(); rc++) {
      // Selection based on the date.
      int modified_date = convert_to_int(sqlitereader.ustring2[rc]);
      switch (editedselection) {
        case nsetToday:
        {
          if (modified_date != currentdate)
            continue;
          break;
        }
        case nsetDateRange:
        {
          if (modified_date < date_from)
            continue;
          if (modified_date > date_to)
            continue;
          break;
        }
        case nsetAny:
        {
          break;
        }
      }
      // Selection based on the category of the note.
      if (!category.empty()) {
        if (category != sqlitereader.ustring4[rc])
          continue;
      }
      // Selection based on project.
      if (currentprojectselection) {
        bool project_ok = false;
        ustring project_in_db = sqlitereader.ustring3[rc];
        extern Settings *settings;
        if (project_in_db == settings->genconfig.project_get())
          project_ok = true;
        // Current notes can use "All".
        if (project_in_db == "All")
          project_ok = true;
        // Only show notes when the project is fine.
        if (!project_ok)
          continue;
      }
      // Get note id.
      gint32 id = convert_to_int(sqlitereader.ustring0[rc]);
      // Sorting on the references that the note refers to.
      unsigned int average_note_reference = 0;
      {
        Parse parse(sqlitereader.ustring1[rc]);
        if (!parse.words.empty()) {
          for (unsigned int i = 0; i < parse.words.size(); i++) {
            average_note_reference += convert_to_int (parse.words[i]);
          }
          average_note_reference /= parse.words.size();
        }
      }
      // Calculate the distance between note and reference.
      // Also see if the cursor must be positioned here.
      int distance = average_note_reference - numerical_currentreference;
      int absolute_distance = ABS (distance);
      if (absolute_distance < minimum_cursor_distance) {
        minimum_cursor_distance = absolute_distance;
        id_cursor = id;
      }
      // Store data. 
      // As we now work with half-verses (10a, 10b), because of the way we select 
      // notes we might have repeating ids. Filter these out.
      if (already_stored_ids.find(id) == already_stored_ids.end()) {
        ids.push_back(id);
        already_stored_ids.insert(id);
        distances.push_back(distance);
      }
    }
    // Sort the notes, based on the distances of the notes to the active reference.
    quick_sort(distances, ids, 0, distances.size());
  }
  catch(exception & ex) {
    gw_critical(ex.what());
  }
  // Close database
  sqlite3_close(db);
}
Example #23
0
void PrintProject2::print()
// Runs the project through xetex and shows it in a pdf viewer.
{
  // Scripture related data.
  // Possible exclusion of books.
  if (portionproject.empty())
    portionproject = myproject->name;
  scriptureportions = new ScripturePortions(portionproject);
  if (scriptureportions->books.empty()) {
    gtkw_dialog_info(NULL, _("There were no books to print\nSelect some books and try again"));
    return;
  }

  // Create the XeTeX object.
  XeTeX xetex (0);

  // Usfm style object.
  Usfm usfm (stylesheet_get_actual ());

  // Collect usfm code for all the books.
  for (unsigned int i = 0; i < scriptureportions->books.size(); i++) {

    // Book id.
    unsigned int book_id = books_english_to_id(scriptureportions->books[i]);

    // Ranges to include.
    WithinReferencesRange inrange;
    {
      vector <unsigned int> chapters_from, chapters_to;
      vector <ustring> verses_from, verses_to;
      select_portion_get_values(portionproject, book_id, scriptureportions->portions[i], chapters_from, verses_from, chapters_to, verses_to);
      inrange.add_portion(book_id, chapters_from, verses_from, chapters_to, verses_to);
    }
    inrange.set_book (book_id);
    inrange.set_chapter (0);
    inrange.set_verse ("0");

    // Open the book.
    vector <ustring> full_book_lines;
    for (unsigned int i2 = 0; i2 < myproject->data.size(); i2++) {
      if (myproject->data[i2].number == book_id) {
        full_book_lines = myproject->data[i2].get_data();
      }
    }

    // Take only those portions the user wishes to print.
    vector <ustring> book_lines;
    for (unsigned int i = 0; i < full_book_lines.size(); i++) {
      ustring line = full_book_lines[i];
      ustring marker = usfm_extract_marker(line);
      if (usfm.is_chapter_number(marker)) {
        inrange.set_chapter (convert_to_int(number_in_string(line)));
        inrange.set_verse ("0");
      }
      if (usfm.is_verse_number(marker)) {
        size_t position = line.find(" ");
        position = CLAMP(position, 0, line.length());
        ustring verse = line.substr(0, position);
        inrange.set_verse (verse);
      }
      if (inrange.in_range()) {
        book_lines.push_back (full_book_lines[i]);
      } else {
        if (marker == "id") {
          ParseLine parseline (full_book_lines[i]);
          if (!parseline.lines.empty ()) {
            book_lines.push_back (parseline.lines[0]);
          }
        }
      }
    }

    // Do text replacements on the lines.
    text_replacement(book_lines);
    // Add the lines to the XeTeX object.
    xetex.add_book (book_id, book_lines);
  }

  // Process the data.
  ustring pdf_file = xetex.run ();

  // Display the pdf file if there is one.
  // There would be none if the formatting process was cancelled by the user.
  if (!pdf_file.empty()) {
    pdfviewer_view (pdf_file);
  }
}
Example #24
0
void notes_get_references_from_editor(GtkTextBuffer * textbuffer, vector < Reference > &references, vector < ustring > &messages)
/*
 Gets all references from the notes editor.
 Normalizes them.
 Produces messages on trouble.
 Handles notes that span more than one chapter.
 */
{
  // Get all lines from the textbuffer.
  vector < ustring > lines;
  textbuffer_get_lines(textbuffer, lines);
  // When discovering a reference from a user's entry, use previous values,
  // so that it becomes quicker for a user to enter new references.
  // If Leviticus 10:11 is already there, and the user wishes to add verse
  // 12 also, he just enters 12 on a line, and that' it.
  Reference previousreference(0);
  for (unsigned int i = 0; i < lines.size(); i++) {
    if (!lines[i].empty()) {
      // Normalize reference.
      Reference reference(0);
      if (reference_discover(previousreference.book, previousreference.chapter, previousreference.verse, lines[i], reference.book, reference.chapter, reference.verse)) {
        ustring ch1, vs1, ch2, vs2;
        if (chapter_span_discover(lines[i], ch1, vs1, ch2, vs2)) {
          // We cross the chapter boundaries. 
          // Store as two or more references, 
          // the first one going up to the end of the chapter, 
          // and the second one starting at the next chapter verse 1,
          // and any chapter in-between.
          extern Settings *settings;
          ProjectConfiguration *projectconfig = settings->projectconfig(settings->genconfig.project_get());
          Reference ref(reference.book, convert_to_int(ch1), vs1);
          ustring lastverse = versification_get_last_verse(projectconfig->versification_get(), reference.book, convert_to_int(ch1));
          ref.verse.append("-" + lastverse);
          references.push_back(ref);
          for (unsigned int ch = convert_to_int(ch1) + 1; ch < convert_to_int(ch2); ch++) {
            Reference ref(reference.book, ch, "1");
            ustring lastverse = versification_get_last_verse(projectconfig->versification_get(), reference.book, ch);
            ref.verse.append("-" + lastverse);
            references.push_back(ref);
          }
          ref.chapter = convert_to_int(ch2);
          ref.verse = "1-" + vs2;
          references.push_back(ref);
          // Store values to discover next reference.
          previousreference.book = reference.book;
          previousreference.chapter = convert_to_int(ch2);
          previousreference.verse = vs2;
        } else {
          // We've a normal reference.
          // Store reference.
          references.push_back(reference);
          // Store values to discover next reference.
          previousreference.book = reference.book;
          previousreference.chapter = reference.chapter;
          previousreference.verse = reference.verse;
        }
      } else {
        messages.push_back(_("Reference ") + lines[i] + _(" is not valid and has been removed."));
      }
    }
  }
}
Example #25
0
string sync_changes (void * webserver_request)
{
  Webserver_Request * request = (Webserver_Request *) webserver_request;
  Sync_Logic sync_logic = Sync_Logic (webserver_request);
  Database_Modifications database_modifications;

  // Check on the credentials.
  if (!sync_logic.credentials_okay ()) return "";

  // Bail out if the change notifications are not now available to clients.
  if (!config_globals_change_notifications_available) {
    request->response_code = 503;
    return "";
  }
  
  // Client makes a prioritized server call: Record the client's IP address.
  sync_logic.prioritized_ip_address_record ();

  // Get the relevant parameters the client may have POSTed to us, the server.
  string user = hex2bin (request->post ["u"]);
  int action = convert_to_int (request->post ["a"]);
  int id = convert_to_int (request->post ["i"]);

  switch (action) {
    case Sync_Logic::changes_delete_modification:
    {
      // The server deletes the change notification.
      database_modifications.deleteNotification (id);
      Database_Logs::log ("Client deletes change notification from server: " + convert_to_string (id), Filter_Roles::translator ());
      request->database_config_user ()->setChangeNotificationsChecksum ("");
      return "";
    }
    case Sync_Logic::changes_get_checksum:
    {
      // The server responds with the possibly cached total checksum for the user's change notifications.
      string checksum = request->database_config_user ()->getChangeNotificationsChecksum ();
      if (checksum.empty ()) {
        checksum = Sync_Logic::changes_checksum (user);
        request->database_config_user ()->setChangeNotificationsChecksum (checksum);
      }
      return checksum;
    }
    case Sync_Logic::changes_get_identifiers:
    {
      // The server responds with the identifiers of all the user's change notifications.
      vector <int> ids = database_modifications.getNotificationIdentifiers (user, false);
      string response;
      for (auto & id : ids) {
        if (!response.empty ()) response.append ("\n");
        response.append (convert_to_string (id));
      }
      return response;
    }
    case Sync_Logic::changes_get_modification:
    {
      // The server responds with the relevant data of the requested modification.
      vector <string> lines;
      // category
      lines.push_back (database_modifications.getNotificationCategory (id));
      // bible
      lines.push_back (database_modifications.getNotificationBible (id));
      // book
      // chapter
      // verse
      Passage passage = database_modifications.getNotificationPassage (id);
      lines.push_back (convert_to_string (passage.book));
      lines.push_back (convert_to_string (passage.chapter));
      lines.push_back (passage.verse);
      // oldtext
      lines.push_back (database_modifications.getNotificationOldText (id));
      // modification
      lines.push_back (database_modifications.getNotificationModification (id));
      // newtext
      lines.push_back (database_modifications.getNotificationNewText (id));
      // Result.
      return filter_string_implode (lines, "\n");
    }
  }

  
  // Bad request.
  // Delay a while to obstruct a flood of bad requests.
  this_thread::sleep_for (chrono::seconds (1));
  request->response_code = 400;
  return "";
}
Example #26
0
void Database_Logs::rotate ()
{
  // Remove the database that was used in older versions of Bibledit.
  // Since February 2016 Bibledit no longer uses a database for storing the journal.
  // Reasons that a database is no longer used:
  // 1. Simpler system.
  // 2. Android has VACUUM errors due to a locked database.
  string old_database_file = database_sqlite_file ("logs2");
  if (file_exists (old_database_file)) {
    filter_url_unlink (old_database_file);
  }

  
  // Use a mechanism that handles huge amounts of entries.
  // The PHP function scandir choked on this or took a very long time.
  // The PHP functions opendir / readdir / closedir handled it better.
  // But now, in C++, with the new journal mechanism, this is no longer relevant.
  string directory = folder ();
  vector <string> files = filter_url_scandir (directory);

  
  // Timestamp for removing older records, depending on whether it's a tiny journal.
#ifdef HAVE_TINYJOURNAL
  int oldtimestamp = filter_date_seconds_since_epoch () - (14400);
#else
  int oldtimestamp = filter_date_seconds_since_epoch () - (6 * 86400);
#endif

  
  // Limit the available the journal entrie count in the filesystem.
  // This speeds up subsequent reading of the Journal by the users.
  // In previous versions of Bibledit, there were certain conditions
  // that led to an infinite loop, as had been noticed at times,
  // and this quickly exhausted the available inodes on the filesystem.
#ifdef HAVE_TINYJOURNAL
  int limitfilecount = files.size () - 200;
#else
  int limitfilecount = files.size () - 2000;
#endif

  
  bool filtered_entries = false;
  for (unsigned int i = 0; i < files.size(); i++) {
    string path = filter_url_create_path (directory, files [i]);

    // Limit the number of journal entries.
    if ((int)i < limitfilecount) {
      filter_url_unlink (path);
      continue;
    }
    
    // Remove expired entries.
    int timestamp = convert_to_int (files [i].substr (0, 10));
    if (timestamp < oldtimestamp) {
      filter_url_unlink (path);
      continue;
    }

    // Filtering of certain entries.
    string entry = filter_url_file_get_contents (path);
    if (journal_logic_filter_entry (entry)) {
      filtered_entries = true;
      filter_url_unlink (path);
      continue;
    }

  }

  if (filtered_entries) {
    log (journal_logic_filtered_message ());
  }
}
Example #27
0
string styles_view (void * webserver_request)
{
  Webserver_Request * request = (Webserver_Request *) webserver_request;
  
  string page;
  
  Assets_Header header = Assets_Header (translate("Style"), webserver_request);
  header.addBreadCrumb (menu_logic_settings_menu (), menu_logic_settings_text ());
  header.addBreadCrumb (styles_indexm_url (), menu_logic_styles_indexm_text ());
  page = header.run ();
  
  Assets_View view;


  Database_Styles database_styles;
  
  
  string sheet = request->query ["sheet"];
  view.set_variable ("sheet", filter_string_sanitize_html (sheet));
  
  
  string style = request->query ["style"];
  view.set_variable ("style", filter_string_sanitize_html (style));

  
  Database_Styles_Item marker_data = database_styles.getMarkerData (sheet, style);
  
  
  // Whether the logged-in user has write access to the stylesheet.
  string username = request->session_logic ()->currentUser ();
  int userlevel = request->session_logic ()->currentLevel ();
  bool write = database_styles.hasWriteAccess (username, sheet);
  if (userlevel >= Filter_Roles::admin ()) write = true;
  

  // The style's name.
  string name = marker_data.name;
  if (request->query.count ("name")) {
    Dialog_Entry dialog_entry = Dialog_Entry ("view", translate("Please enter the name for the style"), name, "name", "");
    dialog_entry.add_query ("sheet", sheet);
    dialog_entry.add_query ("style", style);
    page += dialog_entry.run ();
    return page;
  }
  if (request->post.count ("name")) {
    name = request->post["entry"];
    if (write) database_styles.updateName (sheet, style, name);
  }
  view.set_variable ("name", filter_string_sanitize_html (name));
  

  // The style's info.
  string info = marker_data.info;
  if (request->query.count ("info")) {
    Dialog_Entry dialog_entry = Dialog_Entry ("view", translate("Please enter the description for the style"), info, "info", "");
    dialog_entry.add_query ("sheet", sheet);
    dialog_entry.add_query ("style", style);
    page += dialog_entry.run ();
    return page;
  }
  if (request->post.count("info")) {
    info = request->post["entry"];
    if (write) database_styles.updateInfo (sheet, style, info);
  }
  view.set_variable ("info", filter_string_sanitize_html (info));
  
  
  // The style's category.
  string category = marker_data.category;
  if (request->query.count("category")) {
    category = request->query["category"];
    if (category == "") {
      Dialog_List dialog_list = Dialog_List ("view", translate("Would you like to change the category of this style?"),translate("Here are the various categories:"), translate("Please pick one."));
      dialog_list.add_query ("sheet", sheet);
      dialog_list.add_query ("style", style);
      dialog_list.add_row (styles_logic_category_text ("id"),  "category", "id");
      dialog_list.add_row (styles_logic_category_text ("ith"), "category", "ith");
      dialog_list.add_row (styles_logic_category_text ("ipp"), "category", "ipp");
      dialog_list.add_row (styles_logic_category_text ("ioe"), "category", "ioe");
      dialog_list.add_row (styles_logic_category_text ("t"),   "category", "t");
      dialog_list.add_row (styles_logic_category_text ("h"),   "category", "h");
      dialog_list.add_row (styles_logic_category_text ("cv"),  "category", "cv");
      dialog_list.add_row (styles_logic_category_text ("p"),   "category", "p");
      dialog_list.add_row (styles_logic_category_text ("l"),   "category", "l");
      dialog_list.add_row (styles_logic_category_text ("pe"),  "category", "pe");
      dialog_list.add_row (styles_logic_category_text ("te"),  "category", "te");
      dialog_list.add_row (styles_logic_category_text ("f"),   "category", "f");
      dialog_list.add_row (styles_logic_category_text ("x"),   "category", "x");
      dialog_list.add_row (styles_logic_category_text ("xsn"), "category", "xsn");
      dialog_list.add_row (styles_logic_category_text ("st"),  "category", "st");
      dialog_list.add_row (styles_logic_category_text ("cs"),  "category", "cs");
      dialog_list.add_row (styles_logic_category_text ("sb"),  "category", "sb");
      dialog_list.add_row (styles_logic_category_text ("sf"),  "category", "sf");
      dialog_list.add_row (styles_logic_category_text ("pm"),  "category", "pm");
      dialog_list.add_row (styles_logic_category_text (""),    "category", "");
      page += dialog_list.run ();
      return page;
    } else {
      if (write) database_styles.updateCategory (sheet, style, category);
    }
  }
  view.set_variable ("category", styles_logic_category_text(category));

  
  // The style's type.
  int type = marker_data.type;
  if (request->query.count ("type")) {
    string s = request->query["type"];
    type = convert_to_int (s);
    if (s == "") {
      Dialog_List dialog_list = Dialog_List ("view", translate("Would you like to change the type of this style?"), translate("Here are the various types:"), translate("Please pick one."));
      dialog_list.add_query ("sheet", sheet);
      dialog_list.add_query ("style", style);
      for (int i = 0; i < 99; i++) {
        string text = styles_logic_type_text (i);
        if (text.length () > 2) {
          dialog_list.add_row (text, "type", convert_to_string (i));
        }
      }
      page += dialog_list.run ();
      return page;
    } else {
      if (write) database_styles.updateType (sheet, style, type);
    }
  }
  view.set_variable ("type", convert_to_string (type));
  view.set_variable ("type_text", styles_logic_type_text (type));
  

  // The style's subtype.
  int subtype = marker_data.subtype;
  if (request->query.count ("subtype")) {
    string s = request->query["subtype"];
    subtype = convert_to_int (s);
    if (s == "") {
      Dialog_List dialog_list = Dialog_List ("view", translate("Would you like to change the sub type of this style?"), "", "");
      dialog_list.add_query ("sheet", sheet);
      dialog_list.add_query ("style", style);
      Database_Styles_Item marker_data = database_styles.getMarkerData (sheet, style);
      int type = marker_data.type;
      for (int i = 0; i < 99; i++) {
        string text = styles_logic_subtype_text (type, i);
        if (text.length () > 2) {
          dialog_list.add_row (text, "subtype", convert_to_string (i));
        }
      }
      page += dialog_list.run ();
      return page;
    } else {
      if (write) database_styles.updateSubType (sheet, style, subtype);
    }
  }
  view.set_variable ("subtype",convert_to_string (subtype));
  string subtype_text = styles_logic_subtype_text (type, subtype);
  view.set_variable ("subtype_text", subtype_text);
  if (subtype_text.length () > 2) view.enable_zone ("subtype_text");
  
  
  // The fontsize.
  if (styles_logic_fontsize_is_relevant (type, subtype)) view.enable_zone ("fontsize_relevant");
  float fontsize = marker_data.fontsize;
  if (request->query.count ("fontsize")) {
    Dialog_Entry dialog_entry = Dialog_Entry ("view", translate("Please enter a fontsize between 5 and 60 points"), convert_to_string (fontsize), "fontsize", translate ("The value to enter is just a number, e.g. 12."));
    dialog_entry.add_query ("sheet", sheet);
    dialog_entry.add_query ("style", style);
    page += dialog_entry.run ();
    return page;
  }
  if (request->post.count("fontsize")) {
    float fs = convert_to_float (request->post["entry"]);
    if ((fs >= 5) && (fs <= 60)) {
      fontsize = fs;
      if (write) database_styles.updateFontsize (sheet, style, fontsize);
    }
  }
  view.set_variable ("fontsize", convert_to_string (fontsize));


  // Italics, bold, underline, small caps relevance.
  if (styles_logic_italic_bold_underline_smallcaps_are_relevant (type, subtype)) view.enable_zone ("ibus_relevant");

  
  // Italic.
  int italic = marker_data.italic;
  if (request->query.count ("italic")) {
    string s = request->query["italic"];
    if (s == "") {
      Dialog_List dialog_list = Dialog_List ("view", translate("Would you like to change whether this style is in italics?"), "", "");
      dialog_list.add_query ("sheet", sheet);
      dialog_list.add_query ("style", style);
      Database_Styles_Item marker_data = database_styles.getMarkerData (sheet, style);
      int last_value = ooitOn;
      if (styles_logic_italic_bold_underline_smallcaps_are_full (marker_data.type, marker_data.subtype))
        last_value = ooitToggle;
      for (int i = 0; i <= last_value; i++) {
        dialog_list.add_row (styles_logic_off_on_inherit_toggle_text (i), "italic", convert_to_string (i));
      }
      page += dialog_list.run ();
      return page;
    } else {
      italic = convert_to_int (s);
      if (write) database_styles.updateItalic (sheet, style, italic);
    }
  }
  view.set_variable ("italic", styles_logic_off_on_inherit_toggle_text (italic));
  

  // Bold.
  int bold = marker_data.bold;
  if (request->query.count ("bold")) {
    string s = request->query["bold"];
    if (s == "") {
      Dialog_List dialog_list = Dialog_List ("view", translate("Would you like to change whether this style is in bold?"), "", "");
      dialog_list.add_query ("sheet", sheet);
      dialog_list.add_query ("style", style);
      Database_Styles_Item marker_data = database_styles.getMarkerData (sheet, style);
      int last_value = ooitOn;
      if (styles_logic_italic_bold_underline_smallcaps_are_full (marker_data.type, marker_data.subtype))
        last_value = ooitToggle;
      for (int i = 0; i <= last_value; i++) {
        dialog_list.add_row (styles_logic_off_on_inherit_toggle_text (i), "bold", convert_to_string (i));
      }
      page += dialog_list.run ();
      return page;
    } else {
      bold = convert_to_int (s);
      if (write) database_styles.updateBold (sheet, style, bold);
    }
  }
  view.set_variable ("bold", styles_logic_off_on_inherit_toggle_text (bold));
  

  // Underline.
  int underline = marker_data.underline;
  if (request->query.count ("underline")) {
    string s = request->query["underline"];
    if (s == "") {
      Dialog_List dialog_list = Dialog_List ("view", translate("Would you like to change whether this style is underlined?"), "", "");
      dialog_list.add_query ("sheet", sheet);
      dialog_list.add_query ("style", style);
      Database_Styles_Item marker_data = database_styles.getMarkerData (sheet, style);
      int last_value = ooitOn;
      if (styles_logic_italic_bold_underline_smallcaps_are_full (type, subtype))
        last_value = ooitToggle;
      for (int i = 0; i <= last_value; i++) {
        dialog_list.add_row (styles_logic_off_on_inherit_toggle_text (i), "underline", convert_to_string (i));
      }
      page += dialog_list.run ();
      return page;
    } else {
      underline = convert_to_int (s);
      if (write) database_styles.updateUnderline (sheet, style, underline);
    }
  }
  view.set_variable ("underline", styles_logic_off_on_inherit_toggle_text (underline));

  
  // Small caps.
  int smallcaps = marker_data.smallcaps;
  if (request->query.count ("smallcaps")) {
    string s = request->query["smallcaps"];
    if (s == "") {
      Dialog_List dialog_list = Dialog_List ("view", translate("Would you like to change whether this style is in small caps?"), "", "");
      dialog_list.add_query ("sheet", sheet);
      dialog_list.add_query ("style", style);
      Database_Styles_Item marker_data = database_styles.getMarkerData (sheet, style);
      int last_value = ooitOn;
      if (styles_logic_italic_bold_underline_smallcaps_are_full (marker_data.type, marker_data.subtype))
        last_value = ooitToggle;
      for (int i = 0; i <= last_value; i++) {
        dialog_list.add_row (styles_logic_off_on_inherit_toggle_text (i), "smallcaps", convert_to_string (i));
      }
      page += dialog_list.run ();
      return page;
    } else {
      smallcaps = convert_to_int (s);
      if (write) database_styles.updateSmallcaps (sheet, style, smallcaps);
    }
  }
  view.set_variable ("smallcaps", styles_logic_off_on_inherit_toggle_text (smallcaps));
  
  
  // Superscript.
  if (styles_logic_superscript_is_relevant (type, subtype)) view.enable_zone ("superscript_relevant");
  int superscript = marker_data.superscript;
  if (request->query.count ("superscript")) {
    superscript = convert_to_int (request->query["superscript"]);
    if (write) database_styles.updateSuperscript (sheet, style, superscript);
  }
  view.set_variable ("superscript_value", styles_logic_off_on_inherit_toggle_text (superscript));
  view.set_variable ("superscript_toggle", convert_to_string (!(bool) superscript));
  

  // Whether a list of the following paragraph treats are relevant.
  if (styles_logic_paragraph_treats_are_relevant (type, subtype)) view.enable_zone ("paragraph_treats_relevant");

  
  // Text alignment.
  int justification = marker_data.justification;
  if (request->query.count ("alignment")) {
    Dialog_List dialog_list = Dialog_List ("view", translate("Would you like to change the text alignment of this style?"), "", "");
    dialog_list.add_query ("sheet", sheet);
    dialog_list.add_query ("style", style);
    for (int i = AlignmentLeft; i <= AlignmentJustify; i++) {
      dialog_list.add_row (styles_logic_alignment_text (i), "justification", convert_to_string (i));
    }
    page += dialog_list.run ();
    return page;
  }
  if (request->query.count ("justification")) {
    justification = convert_to_int (request->query["justification"]);
    if (write) database_styles.updateJustification (sheet, style, justification);
  }
  view.set_variable ("justification", styles_logic_alignment_text (justification));
  

  // Space before paragraph.
  float spacebefore = marker_data.spacebefore;
  if (request->query.count ("spacebefore")) {
    Dialog_Entry dialog_entry = Dialog_Entry ("view", translate("Please enter a space of between 0 and 100 mm before the paragraph"), convert_to_string (spacebefore), "spacebefore", translate ("This is the space before, or in other words, above the paragraph. The value to enter is just a number, e.g. 0."));
    dialog_entry.add_query ("sheet", sheet);
    dialog_entry.add_query ("style", style);
    page += dialog_entry.run ();
    return page;
  }
  if (request->post.count ("spacebefore")) {
    spacebefore = convert_to_float (request->post["entry"]);
    if (spacebefore < 0) spacebefore = 0;
    if (spacebefore > 100) spacebefore = 100;
    if (write) database_styles.updateSpaceBefore (sheet, style, spacebefore);
  }
  view.set_variable ("spacebefore", convert_to_string (spacebefore));
  

  // Space after paragraph.
  float spaceafter = marker_data.spaceafter;
  if (request->query.count ("spaceafter")) {
    Dialog_Entry dialog_entry = Dialog_Entry ("view", translate("Please enter a space of between 0 and 100 mm after the paragraph"), convert_to_string (spaceafter), "spaceafter", translate ("This is the space after, or in other words, below the paragraph. The value to enter is just a number, e.g. 0."));
    dialog_entry.add_query ("sheet", sheet);
    dialog_entry.add_query ("style", style);
    page += dialog_entry.run ();
    return page;
  }
  if (request->post.count("spaceafter")) {
    spaceafter = convert_to_float (request->post["entry"]);
    if (spaceafter < 0) spaceafter = 0;
    if (spaceafter > 100) spaceafter = 100;
    if (write) database_styles.updateSpaceAfter (sheet, style, spaceafter);
  }
  view.set_variable ("spaceafter", convert_to_string (spaceafter));
  

  // Left margin.
  float leftmargin = marker_data.leftmargin;
  if (request->query.count ("leftmargin")) {
    Dialog_Entry dialog_entry = Dialog_Entry ("view", translate("Please enter a left margin of between -100 and 100 mm"), convert_to_string (leftmargin), "leftmargin", translate ("This is the left margin of the paragraph. The value to enter is just a number, e.g. 0."));
    dialog_entry.add_query ("sheet", sheet);
    dialog_entry.add_query ("style", style);
    page += dialog_entry.run ();
    return page;
  }
  if (request->post.count("leftmargin")) {
    leftmargin = convert_to_float (request->post ["entry"]);
    if (leftmargin < 0) leftmargin = 0;
    if (leftmargin > 100) leftmargin = 100;
    if (write) database_styles.updateLeftMargin (sheet, style, leftmargin);
  }
  view.set_variable ("leftmargin", convert_to_string (leftmargin));

  
  // Right margin.
  float rightmargin = marker_data.rightmargin;
  if (request->query.count ("rightmargin")) {
    Dialog_Entry dialog_entry = Dialog_Entry ("view", translate("Please enter a right margin of between -100 and 100 mm"), convert_to_string (rightmargin), "rightmargin", translate ("This is the right margin of the paragraph. The value to enter is just a number, e.g. 0."));
    dialog_entry.add_query ("sheet", sheet);
    dialog_entry.add_query ("style", style);
    page += dialog_entry.run ();
    return page;
  }
  if (request->post.count("rightmargin")) {
    rightmargin = convert_to_float (request->post["entry"]);
    if (rightmargin < -100) rightmargin = -100;
    if (rightmargin > 100) rightmargin = 100;
    if (write) database_styles.updateRightMargin (sheet, style, rightmargin);
  }
  view.set_variable ("rightmargin", convert_to_string (rightmargin));
  
  
  // First line indent.
  float firstlineindent = marker_data.firstlineindent;
  if (request->query.count ("firstlineindent")) {
    Dialog_Entry dialog_entry = Dialog_Entry ("view", translate("Please enter a first line indent of between -100 and 100 mm"), convert_to_string (firstlineindent), "firstlineindent", translate ("This is the indent of the first line of the the paragraph. The value to enter is just a number, e.g. 0."));
    dialog_entry.add_query ("sheet", sheet);
    dialog_entry.add_query ("style", style);
    page += dialog_entry.run ();
    return page;
  }
  if (request->post.count ("firstlineindent")) {
    firstlineindent = convert_to_float (request->post["entry"]);
    if (firstlineindent < -100) firstlineindent = -100;
    if (firstlineindent > 100) firstlineindent = 100;
    if (write) database_styles.updateFirstLineIndent (sheet, style, firstlineindent);
  }
  view.set_variable ("firstlineindent", convert_to_string (firstlineindent));

  
  // Columns spanning.
  if (styles_logic_columns_are_relevant (type, subtype)) view.enable_zone ("columns_relevant");
  bool spancolumns = marker_data.spancolumns;
  if (request->query.count ("spancolumns")) {
    spancolumns = convert_to_bool (request->query["spancolumns"]);
    if (write) database_styles.updateSpanColumns (sheet, style, spancolumns);
  }
  view.set_variable ("spancolumns", styles_logic_off_on_inherit_toggle_text (spancolumns));
  view.set_variable ("spancolumns_toggle", convert_to_string (!spancolumns));

  
  // Color.
  if (styles_logic_color_is_relevant (type, subtype)) view.enable_zone ("color_relevant");
  
  string color = marker_data.color;
  if (request->query.count ("textcolor")) {
    color = request->query["color"];
    if (color == "") {
      Dialog_Color dialog_color = Dialog_Color ("view", translate("Please specify a new color"));
      dialog_color.add_query ("textcolor", "true");
      dialog_color.add_query ("sheet", sheet);
      dialog_color.add_query ("style", style);
      page += dialog_color.run ();
      return page;
    } else {
      if (color.find ("#") == string::npos) color.insert (0, "#");
      if (color.length () != 7) color = "#000000";
      if (write) database_styles.updateColor (sheet, style, color);
    }
  }
  view.set_variable ("color", color);

  string backgroundcolor = marker_data.backgroundcolor;
  if (request->query.count ("backgroundcolor")) {
    backgroundcolor = request->query["color"];
    if (backgroundcolor == "") {
      Dialog_Color dialog_color = Dialog_Color ("view", translate("Please specify a new color"));
      dialog_color.add_query ("backgroundcolor", "true");
      dialog_color.add_query ("sheet", sheet);
      dialog_color.add_query ("style", style);
      page += dialog_color.run ();
      return page;
    } else {
      if (backgroundcolor.find ("#") == string::npos) backgroundcolor.insert (0, "#");
      if (backgroundcolor.length () != 7) backgroundcolor = "#FFFFFF";
      if (write) {
        database_styles.updateBackgroundColor (sheet, style, backgroundcolor);
      }
    }
  }
  view.set_variable ("backgroundcolor", backgroundcolor);


  // Whether to print this style.
  if (styles_logic_print_is_relevant (type, subtype)) view.enable_zone ("print_relevant");
  bool print = marker_data.print;
  if (request->query.count ("print")) {
    print = convert_to_bool (request->query["print"]);
    if (write) database_styles.updatePrint (sheet, style, print);
  }
  view.set_variable ("print", styles_logic_off_on_inherit_toggle_text (print));
  view.set_variable ("print_toggle", convert_to_string (!print));
  

  // Userbool1
  string userbool1_function = styles_logic_get_userbool1_text (styles_logic_get_userbool1_function (type, subtype));
  if (userbool1_function.length () > 2) view.enable_zone ("userbool1_relevant");
  view.set_variable ("userbool1_function", userbool1_function);
  bool userbool1 = marker_data.userbool1;
  if (request->query.count ("userbool1")) {
    userbool1 = convert_to_bool (request->query["userbool1"]);
    if (write) database_styles.updateUserbool1 (sheet, style, userbool1);
  }
  view.set_variable ("userbool1_value", styles_logic_off_on_inherit_toggle_text (userbool1));
  view.set_variable ("userbool1_toggle", convert_to_string (!userbool1));

  
  // Userbool2
  string userbool2_function = styles_logic_get_userbool2_text (styles_logic_get_userbool2_function (type, subtype));
  if (userbool2_function.length () > 2) view.enable_zone ("userbool2_relevant");
  view.set_variable ("userbool2_function", userbool2_function);
  bool userbool2 = marker_data.userbool2;
  if (request->query.count ("userbool2")) {
    userbool2 = convert_to_bool (request->query["userbool2"]);
    if (write) database_styles.updateUserbool2 (sheet, style, userbool2);
  }
  view.set_variable ("userbool2_value", styles_logic_off_on_inherit_toggle_text (userbool2));
  view.set_variable ("userbool2_toggle", convert_to_string (!userbool2));

  
  // Userbool3
  string userbool3_function = styles_logic_get_userbool3_text (styles_logic_get_userbool3_function (type, subtype));
  if (userbool3_function.length () > 2) view.enable_zone ("userbool3_relevant");
  view.set_variable ("userbool3_function", userbool3_function);
  bool userbool3 = marker_data.userbool3;
  if (request->query.count ("userbool3")) {
    userbool3 = convert_to_bool (request->query["userbool3"]);
    if (write) database_styles.updateUserbool3 (sheet, style, userbool3);
  }
  view.set_variable ("userbool3_value", styles_logic_off_on_inherit_toggle_text (userbool3));
  view.set_variable ("userbool3_toggle", convert_to_string (!userbool3));

  
  // Userint1.
  int userint1 = marker_data.userint1;
  switch (styles_logic_get_userint1_function (type, subtype)) {
    case UserInt1None :
      break;
    case UserInt1NoteNumbering :
      view.enable_zone ("userint1_notenumbering");
      if (request->query.count ("notenumbering")) {
        Dialog_List dialog_list = Dialog_List ("view", translate("Would you like to change the numbering of the note?"), "", "");
        dialog_list.add_query ("sheet", sheet);
        dialog_list.add_query ("style", style);
        for (int i = NoteNumbering123; i <= NoteNumberingUser; i++) {
          dialog_list.add_row (styles_logic_note_numbering_text (i), "userint1", convert_to_string (i));
        }
        page += dialog_list.run ();
        return page;
      }
      if (request->query.count ("userint1")) {
        userint1 = convert_to_int (request->query["userint1"]);
        if (write) database_styles.updateUserint1 (sheet, style, userint1);
      }
      view.set_variable ("userint1", styles_logic_note_numbering_text (userint1));
      break;
    case UserInt1TableColumnNumber :
      view.enable_zone ("userint1_columnnumber");
      if (request->query.count ("userint1")) {
        Dialog_Entry dialog_entry = Dialog_Entry ("view", translate("Please enter a column number between 1 and 4"), convert_to_string (userint1), "userint1", translate ("This is the column number for the style. The first columm is number 1."));
        dialog_entry.add_query ("sheet", sheet);
        dialog_entry.add_query ("style", style);
        page += dialog_entry.run ();
        return page;
      }
      if (request->post.count ("userint1")) {
        int value = convert_to_int (request->post["entry"]);
        if ((value >= 1) && (value <= 4)) {
          userint1 = value;
          if (write) database_styles.updateUserint1 (sheet, style, userint1);
        }
      }
      view.set_variable ("userint1", convert_to_string (userint1));
      break;
  }
  
  
  // Userint2.
  int userint2 = marker_data.userint2;
  switch (styles_logic_get_userint2_function (type, subtype)) {
    case UserInt2None :
      break;
    case UserInt2NoteNumberingRestart :
      view.enable_zone ("userint2_notenumberingrestart");
      if (request->query.count ("notenumberingrestart")) {
        Dialog_List dialog_list = Dialog_List ("view", translate("Would you like to change when the note numbering restarts?"), "", "");
        dialog_list.add_query ("sheet", sheet);
        dialog_list.add_query ("style", style);
        for (int i = NoteRestartNumberingNever; i <= NoteRestartNumberingEveryChapter; i++) {
          dialog_list.add_row (styles_logic_note_restart_numbering_text (i), "userint2", convert_to_string (i));
        }
        page += dialog_list.run ();
        return page;
      }
      if (request->query.count ("userint2")) {
        userint2 = convert_to_int (request->query["userint2"]);
        if (write) database_styles.updateUserint2 (sheet, style, userint2);
      }
      view.set_variable ("userint2", styles_logic_note_restart_numbering_text (userint2));
      break;
    case UserInt2EndnotePosition :
      view.enable_zone ("userint2_endnoteposition");
      if (request->query.count ("endnoteposition")) {
        Dialog_List dialog_list = Dialog_List ("view", translate("Would you like to change the position where to dump the endnotes?"), "", "");
        dialog_list.add_query ("sheet", sheet);
        dialog_list.add_query ("style", style);
        for (int i = EndNotePositionAfterBook; i <= EndNotePositionAtMarker; i++) {
          dialog_list.add_row (styles_logic_end_note_position_text (i), "userint2", convert_to_string(i));
        }
        page += dialog_list.run ();
        return page;
      }
      if (request->query.count ("userint2")) {
        userint2 = convert_to_int (request->query["userint2"]);
        if (write) database_styles.updateUserint2 (sheet, style, userint2);
      }
      view.set_variable ("userint2", styles_logic_end_note_position_text (userint2));
      break;
  }

  
  // Userint3 not yet used.
  

  // Userstring1.
  string userstring1 = marker_data.userstring1;
  string userstring1_question;
  string userstring1_help;
  switch (styles_logic_get_userstring1_function (type, subtype)) {
    case UserString1None :
      break;
    case UserString1NoteNumberingSequence :
      if (userint1 == NoteNumberingUser) {
        view.enable_zone ("userstring1_numberingsequence");
        userstring1_question = translate("Please enter a new note numbering sequence");
        userstring1_help = translate("This gives a sequence for numbering the notes. When for example § † * is entered, the numbering goes like §, †, *, §, †, *, and so forth. Any sequence of characters can be used. Spaces should separate the characters");
      }
      break;
    case UserString1WordListEntryAddition :
      view.enable_zone ("userstring1_wordlistaddition");
      userstring1_question = translate("Please enter a new addition to the word list entry");
      userstring1_help = translate("This given an optional string to be added after each definition in the body of text. In some Bibles the unusual words are marked with an asterisk and then explained in a glossary. If you would enter the asterisk here, or indeed any string, Bibledit would include this in the exported documents.");
      break;
  }
  if (request->query.count ("userstring1")) {
    Dialog_Entry dialog_entry = Dialog_Entry ("view", userstring1_question, userstring1, "userstring1", userstring1_help);
    dialog_entry.add_query ("sheet", sheet);
    dialog_entry.add_query ("style", style);
    page += dialog_entry.run ();
    return page;
  }
  if (request->post.count ("userstring1")) {
    userstring1 = request->post["entry"];
    if (write) database_styles.updateUserstring1 (sheet, style, userstring1);
  }
  if (userstring1 == "") userstring1 = "--";
  view.set_variable ("userstring1", filter_string_sanitize_html (userstring1));
  

  // Userstring2
  string userstring2 = marker_data.userstring2;
  string userstring2_question;
  string userstring2_info;
  switch (styles_logic_get_userstring2_function (type, subtype)) {
    case UserString2None :
      break;
    case UserString2DumpEndnotesHere :
      if (userint2 == EndNotePositionAtMarker) {
        view.enable_zone ("userstring2_dumpendnotes");
        userstring2_question = translate("Please enter a marker at which the endnotes should be dumped");
        userstring2_info = translate("The marker is to be given without the backslash, e.g. \"zendnotes\".");
      }
      break;
  }
  if (request->query.count ("userstring2")) {
    Dialog_Entry dialog_entry = Dialog_Entry ("view", userstring2_question, userstring2, "userstring2", userstring2_info);
    dialog_entry.add_query ("sheet", sheet);
    dialog_entry.add_query ("style", style);
    page += dialog_entry.run ();
    return page;
  }
  if (request->post.count("userstring2")) {
    userstring2 = request->post["entry"];
    if (write) database_styles.updateUserstring2 (sheet, style, userstring2);
  }
  if (userstring2 == "") userstring2 = "--";
  view.set_variable ("userstring2", filter_string_sanitize_html (userstring2));
  
  // Recreate stylesheets after editing a style.
  if ((request->query.size () != 2) || (request->post.size () != 0)) {
    styles_sheets_create_all ();
  }

  
  // Userstring3 not yet used.
  
  
  page += view.render ("styles", "view");
  
  page += Assets_Page::footer ();
  
  return page;
}
Example #28
0
string resource_organize (void * webserver_request)
{
  Webserver_Request * request = (Webserver_Request *) webserver_request;

  
  string checkbox = request->post ["checkbox"];
  bool checked = convert_to_bool (request->post ["checked"]);

  
  if (request->query.count ("add") || request->post.count ("add")) {
    string add = request->query["add"];
    if (add.empty ()) add = request->post ["add"];
    vector <string> resources = request->database_config_user()->getActiveResources ();
    resources.push_back (add);
    request->database_config_user()->setActiveResources (resources);
    request->database_config_user()->addUpdatedSetting (Sync_Logic::settings_send_resources_organization);
  }
  
  
  if (request->query.count ("remove")) {
    size_t remove = convert_to_int (request->query["remove"]);
    vector <string> resources = request->database_config_user()->getActiveResources ();
    if (remove < resources.size ()) {
      resources.erase (resources.begin () + remove);
    }
    request->database_config_user()->setActiveResources (resources);
    request->database_config_user()->addUpdatedSetting (Sync_Logic::settings_send_resources_organization);
  }

  
  if (request->query.count ("moveup")) {
    size_t moveup = convert_to_int (request->query["moveup"]);
    vector <string> resources = request->database_config_user()->getActiveResources ();
    array_move_up_down (resources, moveup, true);
    request->database_config_user()->setActiveResources (resources);
    request->database_config_user()->addUpdatedSetting (Sync_Logic::settings_send_resources_organization);
  }

  
  if (request->query.count ("movedown")) {
    size_t movedown = convert_to_int (request->query["movedown"]);
    vector <string> resources = request->database_config_user()->getActiveResources ();
    array_move_up_down (resources, movedown, false);
    request->database_config_user()->setActiveResources (resources);
    request->database_config_user()->addUpdatedSetting (Sync_Logic::settings_send_resources_organization);
  }
  
  
  string page;
  Assets_Header header = Assets_Header (translate("Resources"), request);
  page = header.run ();
  Assets_View view;

  
  // Active resources.
  vector <string> active_resources = request->database_config_user()->getActiveResources ();
  string activesblock;
  for (size_t i = 0; i < active_resources.size (); i++) {
    activesblock.append ("<p>");
    activesblock.append ("<a href=\"?remove=" + convert_to_string (i) + "\">");
    activesblock.append (emoji_wastebasket ());
    activesblock.append ("</a>");
    activesblock.append (" ");
    activesblock.append ("<a href=\"?moveup=" + convert_to_string (i) + "\">");
    activesblock.append (unicode_black_up_pointing_triangle ());
    activesblock.append ("</a>");
    activesblock.append ("<a href=\"?movedown=" + convert_to_string (i) + "\">");
    activesblock.append (unicode_black_down_pointing_triangle ());
    activesblock.append ("</a>");
    activesblock.append (" ");
    activesblock.append (active_resources [i]);
    activesblock.append ("</p>");
    activesblock.append ("\n");
  }
  view.set_variable ("activesblock", activesblock);
  
  
  // Context before.
  if (request->query.count ("before")) {
    Dialog_Entry dialog_entry = Dialog_Entry ("organize", translate("Please enter the number of verses"), convert_to_string (request->database_config_user ()->getResourceVersesBefore ()), "before", translate ("How many verses of context to display before the focused verse."));
    page += dialog_entry.run ();
    return page;
  }
  if (request->post.count ("before")) {
    int value = convert_to_int (request->post["entry"]);
    if ((value >= 0) && (value <= 100)) {
      request->database_config_user ()->setResourceVersesBefore (value);
    }
  }
  view.set_variable ("before", convert_to_string (request->database_config_user ()->getResourceVersesBefore ()));

  
  // Context after.
  if (request->query.count ("after")) {
    Dialog_Entry dialog_entry = Dialog_Entry ("organize", translate("Please enter the number of verses"), convert_to_string (request->database_config_user ()->getResourceVersesAfter ()), "after", translate ("How many verses of context to display after the focused verse."));
    page += dialog_entry.run ();
    return page;
  }
  if (request->post.count ("after")) {
    int value = convert_to_int (request->post["entry"]);
    if ((value >= 0) && (value <= 100)) {
      request->database_config_user ()->setResourceVersesAfter (value);
    }
  }
  view.set_variable ("after", convert_to_string (request->database_config_user ()->getResourceVersesAfter ()));

  
  if (checkbox == "related") {
    request->database_config_user ()->setIncludeRelatedPassages (checked);
    return "";
  }
  view.set_variable ("related", get_checkbox_status (request->database_config_user ()->getIncludeRelatedPassages ()));

  
  if (request->query.count ("install")) {
    vector <string> usfm_resources = client_logic_usfm_resources_get ();
    vector <string> original_language_resources = resource_external_get_original_language_resources ();
    vector <string> bible_resources = resource_external_get_bibles ();
    vector <string> commentary_resources = resource_external_get_commentaries ();
    vector <string> general_resources = resource_external_get_general_resources ();
    vector <string> sword_resources = sword_logic_get_available ();
    vector <string> installable_resources;
    installable_resources.insert (installable_resources.end (), usfm_resources.begin (), usfm_resources.end ());
    installable_resources.insert (installable_resources.end (), original_language_resources.begin (), original_language_resources.end ());
    installable_resources.insert (installable_resources.end (), bible_resources.begin (), bible_resources.end ());
    installable_resources.insert (installable_resources.end (), commentary_resources.begin (), commentary_resources.end ());
    installable_resources.insert (installable_resources.end (), general_resources.begin (), general_resources.end ());
    installable_resources.insert (installable_resources.end (), sword_resources.begin (), sword_resources.end ());
    vector <string> installing_resources = Database_Config_General::getResourcesToCache ();
    vector <string> active_resources = request->database_config_user()->getActiveResources ();
    for (auto & resource : active_resources) {
      if (in_array (resource, installable_resources)) {
        if (!in_array (resource, installing_resources)) {
          installing_resources.push_back (resource);
          Database_Config_General::setResourcesToCache (installing_resources);
        }
      }
    }
    tasks_logic_queue (SYNCRESOURCES);
    view.set_variable ("success", translate ("Will install the resources.") + " " + translate ("The journal displays the progress."));
  }

  
#ifdef HAVE_CLIENT
  view.enable_zone ("client");
#endif

  
  page += view.render ("resource", "organize");
  page += Assets_Page::footer ();
  return page;
}
Example #29
0
// handleEmailNew - handles an email received from $from with subject $subject and body $body.
// Returns true if the mail was processed, else false.
// The email is considered to have been processed if it created a new Consultation Note.
bool Notes_Logic::handleEmailNew (string from, string subject, string body)
{
  // Webserver request.
  Webserver_Request * request = (Webserver_Request *) webserver_request;
  // Store the original subject.
  string originalSubject = subject;
  // Check that the subject indicates that a new consultation note is to be created.
  size_t pos = unicode_string_casefold (subject).find ("new note");
  if (pos == string::npos) return false;
  // There is a new note. Remove that bit from the subject.
  if (pos > 0) subject.erase (0, pos + 8);
  // Clean the subject line.
  subject = filter_string_trim (subject);
  subject = filter_string_str_replace (".", " ", subject);
  subject = filter_string_str_replace (":", " ", subject);
  subject = filter_string_str_replace ("   ", " ", subject);
  subject = filter_string_str_replace ("  ", " ", subject);
  // Check that the from address of the email belongs to an existing user.
  from = filter_string_extract_email (from);
  if (!request->database_users()->emailExists (from)) return false;
  string username = request->database_users()->getEmailToUser (from);
  // Extract book, chapter, verse, and note summary from the subject
  int book = -1;
  int chapter = -1;
  int verse = -1;
  string summary;
  vector <string> subjectlines = filter_string_explode (subject, ' ');
  if (!subjectlines.empty()) {
    book = filter_passage_interpret_book (subjectlines[0]);
    subjectlines.erase (subjectlines.begin());
  }
  if (!subjectlines.empty()) {
    chapter = convert_to_int (subjectlines[0]);
    subjectlines.erase (subjectlines.begin());
  }
  if (!subjectlines.empty()) {
    verse = convert_to_int (subjectlines[0]);
    subjectlines.erase (subjectlines.begin());
  }
  summary = filter_string_implode (subjectlines, " ");
  // Check book, chapter, verse, and summary. Give feedback if there's anything wrong.
  string noteCheck;
  if (book <= 0) noteCheck.append (translate("Unknown book"));
  if (chapter < 0) {
    noteCheck.append (" ");
    noteCheck.append (translate("Unknown chapter"));
  }
  if (verse < 0) {
    noteCheck.append (" ");
    noteCheck.append (translate("Unknown verse"));
  }
  if (summary.empty ()) {
    noteCheck.append (" ");
    noteCheck.append (translate("Unknown summary"));
  }
  // Mail user if the note could not be posted.
  Database_Mail database_mail = Database_Mail (webserver_request);
  if (noteCheck != "") {
    subject = translate("Your new note could not be posted");
    database_mail.send (username, subject  + ": " + originalSubject, noteCheck);
    return false;
  }
  // Clean the email's body.
  body = filter_string_extract_body (body);
  // Post the note.
  string sessionuser = request->session_logic()->currentUser ();
  request->session_logic()->setUsername (username);
  Database_Notes database_notes = Database_Notes(webserver_request);
  string bible = request->database_config_user()->getBible ();
  int identifier = database_notes.storeNewNote (bible, book, chapter, verse, summary, body, false);
  handlerNewNote (identifier);
  request->session_logic()->setUsername (sessionuser);
  // Mail confirmation to the username.
  if (request->database_config_user()->getUserNotifyMeOfMyPosts (username)) {
    subject = translate("Your new note was posted");
    database_mail.send (username, subject + ": " + originalSubject, body);
  }
  // Log operation.
  Database_Logs::log ("New note posted : " + body);
  // Job done.
  return true;
}
Example #30
0
string editverse_index (void * webserver_request)
{
  Webserver_Request * request = (Webserver_Request *) webserver_request;
  
  bool touch = request->session_logic ()->touchEnabled ();

  if (request->query.count ("switchbook") && request->query.count ("switchchapter")) {
    int switchbook = convert_to_int (request->query ["switchbook"]);
    int switchchapter = convert_to_int (request->query ["switchchapter"]);
    Ipc_Focus::set (request, switchbook, switchchapter, 1);
    Navigation_Passage::recordHistory (request, switchbook, switchchapter, 1);
  }
  
  string page;
  
  Assets_Header header = Assets_Header (translate("Edit USFM"), request);
  header.setNavigator ();
  if (touch) header.jQueryTouchOn ();
  header.notifItOn ();
  header.addBreadCrumb (menu_logic_translate_menu (), menu_logic_translate_text ());
  page = header.run ();
  
  Assets_View view;
  
  if (request->query.count ("changebible")) {
    string changebible = request->query ["changebible"];
    if (changebible == "") {
      Dialog_List dialog_list = Dialog_List ("index", translate("Select which Bible to open in the editor"), "", "");
      vector <string> bibles = access_bible_bibles (request);
      for (auto bible : bibles) {
        dialog_list.add_row (bible, "changebible", bible);
      }
      page += dialog_list.run();
      return page;
    } else {
      request->database_config_user()->setBible (changebible);
    }
  }
  
  // Get active Bible, and check read access to it.
  // If needed, change Bible to one it has read access to.
  string bible = access_bible_clamp (request, request->database_config_user()->getBible ());
  if (request->query.count ("bible")) bible = access_bible_clamp (request, request->query ["bible"]);
  view.set_variable ("bible", bible);
  
  // Store the active Bible in the page's javascript.
  view.set_variable ("navigationCode", Navigation_Passage::code (bible));
  
  string chapterLoaded = locale_logic_text_loaded ();
  string chapterSaving = locale_logic_text_saving ();
  string chapterSaved = locale_logic_text_saved ();
  string chapterRetrying = locale_logic_text_retrying ();
  string script =
  "var verseEditorVerseLoaded = '" + chapterLoaded + "';\n"
  "var verseEditorVerseSaving = '" + chapterSaving + "';\n"
  "var verseEditorVerseSaved = '" + chapterSaved + "';\n"
  "var verseEditorChapterRetrying = '" + chapterRetrying + "';\n"
  "var verseEditorWriteAccess = true;"
  "var unsentBibleDataTimeoutWarning = '" + bible_logic_unsent_unreceived_data_warning (false) + "';\n";
  config_logic_swipe_enabled (webserver_request, script);
  view.set_variable ("script", script);
  
  string cls = Filter_Css::getClass (bible);
  string font = Fonts_Logic::getTextFont (bible);
  int direction = Database_Config_Bible::getTextDirection (bible);
  int lineheight = Database_Config_Bible::getLineHeight (bible);
  int letterspacing = Database_Config_Bible::getLetterSpacing (bible);
  view.set_variable ("custom_class", cls);
  view.set_variable ("custom_css", Filter_Css::getCss (cls,
                                                             Fonts_Logic::getFontPath (font),
                                                             direction,
                                                             lineheight,
                                                             letterspacing));
  
  // Whether to enable fast Bible editor switching.
  if (request->database_config_user ()->getFastEditorSwitchingAvailable ()) {
    view.enable_zone ("fastswitcheditor");
  }
  
  page += view.render ("editverse", "index");
  
  page += Assets_Page::footer ();
  
  return page;
}