示例#1
0
// Indexes a $bible $book $chapter for searching.
void search_logic_index_chapter (string bible, int book, int chapter)
{
  Database_Bibles database_bibles;
  
  string usfm = database_bibles.getChapter (bible, book, chapter);
  string stylesheet = Database_Config_Bible::getExportStylesheet (bible);

  vector <string> index;
  
  set <string> already_processed;
  
  vector <int> verses = usfm_get_verse_numbers (usfm);
  
  for (auto verse : verses) {

    string raw_usfm = filter_string_trim (usfm_get_verse_text (usfm, verse));

    // In case of combined verses, the bit of USFM may have been indexed already.
    // Skip it in that case.
    if (already_processed.find (raw_usfm) != already_processed.end ()) continue;
    already_processed.insert (raw_usfm);

    index.push_back (search_logic_verse_separator ());
    index.push_back (convert_to_string (verse));
    index.push_back (search_logic_index_separator ());

    index.push_back (raw_usfm);
    
    string usfm_lower = unicode_string_casefold (raw_usfm);

    index.push_back (search_logic_index_separator ());

    index.push_back (usfm_lower);
    
    // Text filter for getting the plain text.
    Filter_Text filter_text = Filter_Text (bible);
    filter_text.text_text = new Text_Text ();
    filter_text.initializeHeadingsAndTextPerVerse (true);
    filter_text.addUsfmCode (raw_usfm);
    filter_text.run (stylesheet);

    string raw_plain;
    // Add the clean verse texts.
    map <int, string> texts = filter_text.getVersesText ();
    for (auto & element : texts) {
      raw_plain.append (element.second + "\n");
    }
    // Add any clean headings.
    map <int, string> headings = filter_text.verses_headings;
    for (auto & element : headings) {
      raw_plain.append (element.second + "\n");
    }
    // Add any footnotes.
    raw_plain.append (filter_text.text_text->getnote ());
    // Clean up.
    raw_plain = filter_string_trim (raw_plain);
    
    index.push_back (search_logic_index_separator ());

    index.push_back (raw_plain);
    
    string plain_lower = unicode_string_casefold (raw_plain);

    index.push_back (search_logic_index_separator ());

    index.push_back (plain_lower);
  }
  
  index.push_back (search_logic_index_separator ());
  
  // Store everything.
  string path = search_logic_chapter_file (bible, book, chapter);
  filter_url_file_put_contents (path, filter_string_implode (index, "\n"));
}
示例#2
0
void mechon_mamre_action_page (HtmlWriter2& htmlwriter)
{
  htmlwriter.heading_open (3);
  htmlwriter.text_add ("Hebrew import from Mechon Mamre");
  htmlwriter.heading_close ();

  vector <ustring> messages;
  bool keep_going = true;

  // Locate the downloaded file.
  ustring ct005zipfilename = gw_build_filename (g_get_home_dir (), "ct005.zip");
  messages.push_back ("Looking for file " + ct005zipfilename);
  if (!g_file_test (ct005zipfilename.c_str(), G_FILE_TEST_IS_REGULAR)) {
    ct005zipfilename.clear();
  }
  if (ct005zipfilename.empty()) {
    ct005zipfilename = gw_build_filename (g_get_home_dir (), "Desktop", "ct005.zip");
    messages.push_back ("Looking for file " + ct005zipfilename);
    if (!g_file_test (ct005zipfilename.c_str(), G_FILE_TEST_IS_REGULAR)) {
      ct005zipfilename.clear();
    }
  }
  if (ct005zipfilename.empty()) {
    ct005zipfilename = gw_build_filename (g_get_home_dir (), "Downloads", "ct005.zip");
    messages.push_back ("Looking for file " + ct005zipfilename);
    if (!g_file_test (ct005zipfilename.c_str(), G_FILE_TEST_IS_REGULAR)) {
      ct005zipfilename.clear();
    }
  }
  if (ct005zipfilename.empty()) {
    messages.push_back ("Can't find Hebrew input file");
    keep_going = false;
  }
  if (keep_going) {
    messages.push_back ("Using file " + ct005zipfilename);
  }

  // Unpack the zipped file.
  ustring directory;
  if (keep_going) {
    directory = gw_build_filename (Directories->get_temp (), "uncompress");
    unix_rmdir (directory);
    gw_mkdir_with_parents (directory);
    if (!uncompress (ct005zipfilename, directory)) {
      messages.push_back ("Could not unpack the file");
      keep_going = false;
    }
    messages.push_back ("Unpacking into folder " + directory);
  }

  // Show the readme file.
  if (keep_going) {
    ustring readmefile = gw_build_filename (directory, "readme.txt");
    ReadText rt (readmefile, true, true);
    ustring line;
    for (unsigned int i = 0; i < rt.lines.size(); i++) {
      if (rt.lines[i].empty()) {
        if (!line.empty()) {
          messages.push_back (line);
          line.clear();
        }
      } else {
        line.append (rt.lines[i] + " ");
      }
    }
    messages.push_back (line);
  }

  // Look for the directory where all the html files reside.
  if (keep_going) {
    directory = gw_build_filename (directory, "c", "ct");
    if (!g_file_test (directory.c_str(), G_FILE_TEST_IS_DIR)) {
      messages.push_back ("Can't find data in directory " + directory);
    }
    messages.push_back ("Looking for data in directory " + directory);
  }
  
  // Get a list of the html files that have the data.
  vector <ustring> files;
  if (keep_going) {
    ReadFiles rf (directory, "c", ".htm");
    for (unsigned int i = 0; i < rf.files.size(); i++) {
      ustring filename = gw_build_filename (directory, rf.files[i]);
      // Check on a few characteristics.
      if (mechon_mamre_copyright(filename)) {
        unsigned int digitcount = digit_count_in_string(rf.files[i]);
        if ((digitcount == 3) || (digitcount == 4)) {
          files.push_back(filename);
        }
      }
    }
  }

  // Create a new Bible into which to import the data.
  ustring bible = "Hebrew Mechon Mamre";
  if (keep_going) {
    if (project_exists (bible)) {
      messages.push_back ("A Bible called \"" + bible + "\" already exists");
      keep_going = false;      
    } else {
      project_create_restore (bible, "");
      messages.push_back ("Creating a new Bible called \"" + bible + "\"");
      // Make a couple of settings.
      extern Settings * settings;
      ProjectConfiguration * projectconfig = settings->projectconfig (bible);
      projectconfig->versification_set ("Original");
      projectconfig->editable_set (false);
      projectconfig->right_to_left_set (true);
      projectconfig->spelling_check_set (false);
    }
  }

  // Store all the chapters 0 in each book.
  if (keep_going) {
    vector <unsigned int> books = books_type_to_ids(btOldTestament);
    ProgressWindow progresswindow ("Creating books", false);
    progresswindow.set_iterate (0, 1, books.size());
    for (unsigned int bk = 0; bk < books.size(); bk++) {
      progresswindow.iterate ();
      vector <ustring> usfm;
      usfm.push_back ("\\id " + books_id_to_paratext (books[bk]));
      CategorizeChapterVerse ccv (usfm);      
      project_store_chapter (bible, books[bk], ccv);
    }  
  }

  // Store all the chapters.
  if (keep_going) {
    ProgressWindow progresswindow ("Importing chapters", false);
    progresswindow.set_iterate (0, 1, files.size());
    for (unsigned int i = 0; i < files.size(); i++) {
      progresswindow.iterate ();
      unsigned int book = 0;
      unsigned int chapter = 0;
      mechon_mamre_extract_book_chapter (files[i], book, chapter);
      vector <ustring> contents = mechon_mamre_extract_contents (files[i], chapter);
      CategorizeChapterVerse ccv (contents);
      project_store_chapter (bible, book, ccv);
      messages.push_back ("Importing " + books_id_to_english (book) + " " + convert_to_string (chapter) + " from file " + files[i]);
    }
  }

  // Write accumulated messages.
  htmlwriter.heading_open (3);
  if (keep_going) {
    htmlwriter.text_add ("Success! Bible \"" + bible + "\" was created");
  } else {
    htmlwriter.text_add ("Error!");
  }
  htmlwriter.heading_close ();
  if (keep_going) {
    htmlwriter.paragraph_open ();
    htmlwriter.text_add ("To view the Hebrew text, open the Bible in the editor. Optionally set the font for better display of the Hebrew text. A donation made to Mechon Mamre will support their work.");
    htmlwriter.paragraph_close ();
  }
  for (unsigned int i = 0; i < messages.size(); i++) {
    htmlwriter.paragraph_open ();
    htmlwriter.text_add (messages[i]);
    htmlwriter.paragraph_close ();
  }  
  
  // Write OK.
  htmlwriter.paragraph_open ();
  htmlwriter.hyperlink_add ("ok", "Ok");
  htmlwriter.paragraph_close ();
}
示例#3
0
string workbench_index (void * webserver_request)
{
  Webserver_Request * request = (Webserver_Request *) webserver_request;
  vector <string> desktops = workbench_get_names (request);

  
  // Set the requested desktop as the active one.
  if (request->query.count ("bench")) {
    unsigned int bench = convert_to_int (request->query ["bench"]);
    if (bench < desktops.size ()) {
      string workbench = desktops [bench];
      request->database_config_user()->setActiveWorkbench (workbench);
    }
  }
  
  
  // Check that the active desktop exists, else set the first available desktop as the active one.
  {
    string desktop = request->database_config_user ()->getActiveWorkbench ();
    if (!in_array (desktop, desktops)) {
      if (!desktops.empty ()) {
        request->database_config_user ()->setActiveWorkbench (desktops [0]);
      }
    }
  }
  
  
  // Create default set of desktops if there are none.
  bool create = desktops.empty ();
  if (!create) {
    create = (desktops [0] == workbench_get_default_name ());
  }
  if (create) {
    workbench_create_defaults (webserver_request);
  }

  
  // In case the desktop is opened from a consultation note email,
  // read the note, and set the active passage to the passage the note refers to.
  int noteid = convert_to_int (request->query ["note"]);
  if (noteid) {
    Database_Notes database_notes (webserver_request);
    vector <Passage> passages = database_notes.getPassages (noteid);
    if (!passages.empty ()) {
      Ipc_Focus::set (webserver_request, passages[0].book, passages[0].chapter, convert_to_int (passages[0].verse));
      Navigation_Passage::recordHistory (webserver_request, passages[0].book, passages[0].chapter, convert_to_int (passages[0].verse));
    }
  }
  
  
  string page;
  Assets_Header header = Assets_Header (translate("Desktop"), request);
  header.setNavigator ();
  header.setFadingMenu (menu_logic_desktop_category (webserver_request));
  page = header.run ();
  Assets_View view;

  
  map <int, string> urls = workbench_get_urls (request, true);
  map <int, string> widths = workbench_get_widths (request);
  for (unsigned int key = 0; key < 15; key++) {
    string url = urls [key];
    string width = widths [key];
    int row = round (key / 5) + 1;
    int column = key % 5 + 1;
    string variable = "url" + convert_to_string (row) + convert_to_string (column);
    view.set_variable (variable, url);
    variable = "width" + convert_to_string (row) + convert_to_string (column);
    view.set_variable (variable, width);
    if (convert_to_int (width) > 0) view.enable_zone (variable);
  }
  
  
  map <int, string> heights = workbench_get_heights (request);
  for (unsigned int key = 0; key < 3; key++) {
    string height = heights [key];
    int row = key + 1;
    string variable = "height" + convert_to_string (row);
    view.set_variable (variable, height);
    if (convert_to_int (height) > 0) view.enable_zone (variable);
  }
  
  
  string workbenchwidth = workbench_get_entire_width (request);
  if (!workbenchwidth.empty ()) {
    workbenchwidth.insert (0, "width: ");
    workbenchwidth.append (";");
  }
  view.set_variable ("workbenchwidth", workbenchwidth);
  
  
  // The rendered template disables framekillers through the "sandbox" attribute on the iframe elements.
  page += view.render ("workbench", "index");
  page += Assets_Page::footer ();
  return page;
}
示例#4
0
string manage_users (void * webserver_request)
{
  Webserver_Request * request = (Webserver_Request *) webserver_request;

  
  bool user_updated = false;
  bool privileges_updated = false;
  
  
  string page;
  Assets_Header header = Assets_Header (translate("Users"), webserver_request);
  header.addBreadCrumb (menu_logic_settings_menu (), menu_logic_settings_text ());
  page = header.run ();

  
  Assets_View view;


  int myLevel = request->session_logic ()->currentLevel ();
  
  
  // New user creation.
  if (request->query.count ("new")) {
    Dialog_Entry dialog_entry = Dialog_Entry ("users", translate("Please enter a name for the new user"), "", "new", "");
    page += dialog_entry.run ();
    return page;
  }
  if (request->post.count ("new")) {
    string user = request->post["entry"];
    if (request->database_users ()->usernameExists (user)) {
      page += Assets_Page::error (translate("User already exists"));
    } else {
      request->database_users ()->addNewUser(user, user, Filter_Roles::member (), "");
      user_updated = true;
      page += Assets_Page::success (translate("User created"));
    }
  }
  
  
  // The user to act on.
  string objectUsername = request->query["user"];
  int objectUserLevel = request->database_users ()->getUserLevel (objectUsername);
  
  
  // Delete a user.
  if (request->query.count ("delete")) {
    string role = Filter_Roles::text (objectUserLevel);
    string email = request->database_users ()->getUserToEmail (objectUsername);
    string message = "Deleted user " + objectUsername + " with role " + role + " and email " + email;
    Database_Logs::log (message, Filter_Roles::admin ());
    request->database_users ()->removeUser (objectUsername);
    user_updated = true;
    database_privileges_client_remove (objectUsername);
    page += Assets_Page::success (message);
    // Also remove any privileges for this user.
    // In particular for the Bible privileges this is necessary,
    // beause if old users remain in the privileges storage,
    // then a situation where no user has any privileges to any Bible,
    // and thus all relevant users have all privileges,
    // can never be achieved again.
    Database_Privileges::removeUser (objectUsername);
    // Remove any login tokens the user might have had: Just to clean things up.
    Database_Login::removeTokens (objectUsername);
    // Remove any settings for the user.
    // The advantage of this is that when a user is removed, all settings are gone,
    // so when the same user would be created again, all settings will go back to their defaults.
    request->database_config_user ()->remove (objectUsername);
  }
  
  
  // The user's role.
  if (request->query.count ("level")) {
    string level = request->query ["level"];
    if (level == "") {
      Dialog_List dialog_list = Dialog_List ("users", translate("Select a role for") + " " + objectUsername, "", "");
      dialog_list.add_query ("user", objectUsername);
      for (int i = Filter_Roles::lowest (); i <= Filter_Roles::highest (); i++) {
        if (i <= myLevel) {
          dialog_list.add_row (Filter_Roles::text (i), "level", convert_to_string (i));
        }
      }
      page += dialog_list.run ();
      return page;
    } else {
      request->database_users ()->updateUserLevel (objectUsername, convert_to_int (level));
      user_updated = true;
    }
  }
  
  
  // User's email address.
  if (request->query.count ("email")) {
    string email = request->query ["email"];
    if (email == "") {
      string question = translate("Please enter an email address for") + " " + objectUsername;
      string value = request->database_users ()->getUserToEmail (objectUsername);
      Dialog_Entry dialog_entry = Dialog_Entry ("users", question, value, "email", "");
      dialog_entry.add_query ("user", objectUsername);
      page += dialog_entry.run ();
      return page;
    }
  }
  if (request->post.count ("email")) {
    string email = request->post["entry"];
    if (filter_url_email_is_valid (email)) {
      page += Assets_Page::success (translate("Email address was updated"));
      request->database_users ()->updateUserEmail (objectUsername, email);
      user_updated = true;
    } else {
      page += Assets_Page::error (translate("The email address is not valid"));
    }
  }
  
  
  // Fetch all available Bibles.
  vector <string> allbibles = request->database_bibles ()->getBibles ();
  
  
  // Add Bible to user account.
  if (request->query.count ("addbible")) {
    string addbible = request->query["addbible"];
    if (addbible == "") {
      Dialog_List dialog_list = Dialog_List ("users", translate("Would you like to grant the user access to a Bible?"), "", "");
      dialog_list.add_query ("user", objectUsername);
      for (auto bible : allbibles) {
        dialog_list.add_row (bible, "addbible", bible);
      }
      page += dialog_list.run ();
      return page;
    } else {
      Assets_Page::success (translate("The user has been granted access to this Bible"));
      // Write access depends on whether it's a translator role or higher.
      bool write = (objectUserLevel >= Filter_Roles::translator ());
      Database_Privileges::setBible (objectUsername, addbible, write);
      user_updated = true;
      privileges_updated = true;
    }
  }
  
  
  // Remove Bible from user.
  if (request->query.count ("removebible")) {
    string removebible = request->query ["removebible"];
    Database_Privileges::removeBibleBook (objectUsername, removebible, 0);
    user_updated = true;
    privileges_updated = true;
    Assets_Page::success (translate("The user no longer has access to this Bible"));
  }
  
  
  // Login on behalf of another user.
  if (request->query.count ("login")) {
    request->session_logic ()->switchUser (objectUsername);
    redirect_browser (request, session_switch_url ());
    return "";
  }
  
  
  // User accounts to display.
  vector <string> tbody;
  // Retrieve assigned users.
  vector <string> users = access_user_assignees (webserver_request);
  for (auto & username : users) {
    // Gather details for this user account.
    objectUserLevel = request->database_users ()->getUserLevel (username);
    string namedrole = Filter_Roles::text (objectUserLevel);
    string email = request->database_users ()->getUserToEmail (username);
    if (email == "") email = "--";
    tbody.push_back ("<tr>");
    tbody.push_back ("<td><a href=\"?user="******"&delete\">✗</a> " + username + "</td>");
    tbody.push_back ("<td>│</td>");
    tbody.push_back ("<td><a href=\"?user="******"&level\">" + namedrole + "</a></td>");
    tbody.push_back ("<td>│</td>");
    tbody.push_back ("<td><a href=\"?user="******"&email\">" + email + "</a></td>");
    tbody.push_back ("<td>│</td>");
    tbody.push_back ("<td>");

    if (objectUserLevel < Filter_Roles::manager ()) {
      for (auto & bible : allbibles) {
        bool exists = Database_Privileges::getBibleBookExists (username, bible, 0);
        if (exists) {
          bool read, write;
          Database_Privileges::getBible (username, bible, read, write);
          if  (objectUserLevel >= Filter_Roles::translator ()) write = true;
          tbody.push_back ("<a href=\"?user="******"&removebible=" + bible + "\">✗</a>");
          tbody.push_back ("<a href=\"/bible/settings?bible=" + bible + "\">" + bible + "</a>");
          tbody.push_back ("<a href=\"write?user="******"&bible=" + bible + "\">");
          int readwritebooks = 0;
          vector <int> books = request->database_bibles ()->getBooks (bible);
          for (auto book : books) {
            Database_Privileges::getBibleBook (username, bible, book, read, write);
            if (write) readwritebooks++;
          }
          tbody.push_back ("(" + convert_to_string (readwritebooks) + "/" + convert_to_string (books.size ()) + ")");
          tbody.push_back ("</a>");
          tbody.push_back ("|");
        }
      }
    }
    if (objectUserLevel >= Filter_Roles::manager ()) {
      // Managers and higher roles have access to all Bibles.
      tbody.push_back ("(" + translate ("all") + ")");
    } else {
      tbody.push_back ("<a href=\"?user="******"&addbible=\">➕</a>");
    }
    tbody.push_back ("</td>");

    tbody.push_back ("<td>│</td>");

    tbody.push_back ("<td>");
    if (objectUserLevel >= Filter_Roles::manager ()) {
      // Managers and higher roles have all privileges.
      tbody.push_back ("(" + translate ("all") + ")");
    } else {
      tbody.push_back ("<a href=\"privileges?user="******"\">" + translate ("edit") + "</a>");
    }
    tbody.push_back ("</td>");
    
    // Logging for another user.
    if (myLevel > objectUserLevel) {
      tbody.push_back ("<td>│</td>");
      tbody.push_back ("<td>");
      tbody.push_back ("<a href=\"?user="******"&login\">" + translate ("Login") + "</a>");
      tbody.push_back ("</td>");
    }
    
    tbody.push_back ("</tr>");
  }

  view.set_variable ("tbody", filter_string_implode (tbody, "\n"));

  page += view.render ("manage", "users");

  page += Assets_Page::footer ();
  
  if (user_updated) notes_logic_maintain_note_assignees (true);
  if (privileges_updated) database_privileges_client_create (objectUsername, true);

  return page;
}
示例#5
0
// This function creates a text-based burndown chart for sprint $bible / $year / $month.
string sprint_create_burndown_chart (string bible, int year, int month)
{
  // Get the seconds for the first of the month.
  int seconds = filter_date_seconds_since_epoch (year, month, 1);
  
  // The business days in the month for on the X-axis.
  vector <int> days_in_month;
  for (unsigned int day = 1; day <= 31; day++) {
    int mymonth = filter_date_numerical_month (seconds);
    if (mymonth == month) {
      if (filter_date_is_business_day (year, month, day)) {
        days_in_month.push_back (day);
      }
    }
    seconds += 86400;
  }
  
  // Assemble history of this sprint.
  Database_Sprint database_sprint = Database_Sprint ();
  vector <Database_Sprint_Item> history = database_sprint.getHistory (bible, year, month);
  map <int, int> data;
  for (auto day : days_in_month) {
    data [day] = 0;
    for (auto item : history) {
      if (day == item.day) {
        int tasks = item.tasks;
        int complete = item.complete;
        tasks = round (tasks * (100 - complete) / 100);
        data [day] = tasks;
      }
    }
  }
  
  vector <string> lines;
  lines.push_back ("<table class='burndown'>");
  lines.push_back ("<tr>");
  for (auto element : data) {
    int tasks = element.second;
    string text;
    for (int i = 0; i < tasks; i++) text.append ("▓<br>");
    lines.push_back ("<td  style=\"vertical-align: bottom;\" class='day'>" + text + "</td>");
  }
  lines.push_back ("</tr>");
  
  // Write number of days along the X-axis.
  lines.push_back ("<tr>");
  for (auto element : data) {
    int day = element.first;
    lines.push_back ("<td class='day'>" + convert_to_string (day) + "</td>");
  }
  lines.push_back ("</tr>");
                                      
  // Write "days" below the X-axis.
  lines.push_back ("<tr>");
  int columncount = data.size ();
  string text = translate("days");
  lines.push_back ("<td colspan=\"" + convert_to_string (columncount) + "\">" + text + "</td>");
  lines.push_back ("</tr>");
                                    
  lines.push_back ("</table>");
                                                                      
  string chart = filter_string_implode (lines, "\n");
  return chart;
}
示例#6
0
void sendreceive_changes ()
{
  if (sendreceive_changes_watchdog) {
    int time = filter_date_seconds_since_epoch ();
    if (time < (sendreceive_changes_watchdog + 900)) {
      Database_Logs::log (sendreceive_changes_text () + translate("Still busy"), Filter_Roles::translator ());
      return;
    }
    Database_Logs::log (sendreceive_changes_text () + translate("Watchdog timeout"), Filter_Roles::translator ());
  }
  sendreceive_changes_kick_watchdog ();
  config_globals_syncing_changes = true;

  
  Database_Logs::log (sendreceive_changes_sendreceive_text (), Filter_Roles::translator ());
  

  Webserver_Request request;
  Sync_Logic sync_logic = Sync_Logic (&request);
  Database_Modifications database_modifications;
  
  
  if (!database_modifications.healthy ()) {
    Database_Logs::log (sendreceive_changes_text () + translate("Recreate damaged modifications database"), Filter_Roles::translator ());
    database_modifications.erase ();
    database_modifications.create ();
  }
  
  
  string response = client_logic_connection_setup ();
  int iresponse = convert_to_int (response);
  if (iresponse < Filter_Roles::guest () || iresponse > Filter_Roles::admin ()) {
    Database_Logs::log (sendreceive_changes_text () + translate("Failure to initiate connection"), Filter_Roles::translator ());
    send_receive_changes_done ();
    return;
  }
  
  
  // Set the correct user in the session: The sole user on the Client.
  vector <string> users = request.database_users ()->getUsers ();
  if (users.empty ()) {
    Database_Logs::log (translate("No user found"), Filter_Roles::translator ());
    send_receive_changes_done ();
    return;
  }
  string user = users [0];
  request.session_logic ()->setUsername (user);
  string password = request.database_users ()->getmd5 (user);
  
  
  // The basic request to be POSTed to the server.
  // It contains the user's credentials.
  map <string, string> post;
  post ["u"] = bin2hex (user);
  post ["p"] = password;
  post ["l"] = convert_to_string (request.database_users ()->getUserLevel (user));
  
  
  // Error variables.
  string error;
  bool communication_errors = false;
  
  
  // Server URL to call.
  string address = Database_Config_General::getServerAddress ();
  int port = Database_Config_General::getServerPort ();
  string url = client_logic_url (address, port, sync_changes_url ());
  
  
  // Send the removed change notifications to the server.
  vector <int> ids = request.database_config_user ()->getRemovedChanges ();
  if (!ids.empty ()) Database_Logs::log (sendreceive_changes_text () + "Sending removed notifications: " + convert_to_string (ids.size()), Filter_Roles::translator ());
  for (auto & id : ids) {
    post ["a"] = convert_to_string (Sync_Logic::changes_delete_modification);
    post ["i"] = convert_to_string (id);
    response = sync_logic.post (post, url, error);
    if (!error.empty ()) {
      communication_errors = true;
      Database_Logs::log (sendreceive_changes_text () + "Failure sending removed notification: " + error, Filter_Roles::translator ());
    }
    else {
      request.database_config_user ()->removeRemovedChange (id);
    }
  }
  
  
  if (communication_errors) {
    Database_Logs::log (sendreceive_changes_text () + translate("Not downloading change notifications due to communication error"), Filter_Roles::translator ());
    send_receive_changes_done ();
    return;
  }
  
  
  // Compare the total checksum for the change notifications for the active user on client and server.
  // Checksum is cached for future re-use.
  // Take actions based on that.
  string client_checksum = request.database_config_user ()->getChangeNotificationsChecksum ();
  if (client_checksum.empty ()) {
    client_checksum = Sync_Logic::changes_checksum (user);
    request.database_config_user ()->setChangeNotificationsChecksum (client_checksum);
  }
  string server_checksum;
  post ["a"] = convert_to_string (Sync_Logic::changes_get_checksum);
  response = sync_logic.post (post, url, error);
  if (!error.empty ()) {
    Database_Logs::log (sendreceive_changes_text () + "Failure receiving checksum: " + error, Filter_Roles::translator ());
    send_receive_changes_done ();
    return;
  }
  server_checksum = response;
  if (client_checksum == server_checksum) {
    Database_Logs::log (sendreceive_changes_up_to_date_text (), Filter_Roles::translator ());
    send_receive_changes_done ();
    return;
  }
  
  
  // Get all identifiers for the notifications on the server for the user.
  // Get the identifiers on the client.
  vector <int> client_identifiers = database_modifications.getNotificationIdentifiers (user, false);
  vector <int> server_identifiers;
  post ["a"] = convert_to_string (Sync_Logic::changes_get_identifiers);
  response = sync_logic.post (post, url, error);
  if (!error.empty ()) {
    Database_Logs::log (sendreceive_changes_text () + "Failure receiving identifiers: " + error, Filter_Roles::translator ());
    send_receive_changes_done ();
    return;
  }
  {
    vector <string> ids = filter_string_explode (response, '\n');
    for (auto & id : ids) server_identifiers.push_back (convert_to_int (id));
  }

  
  // Any identifiers on the client, but not on the server, remove them from the client.
  vector <int> remove_identifiers = filter_string_array_diff (client_identifiers, server_identifiers);
  for (auto & id : remove_identifiers) {
    database_modifications.deleteNotification (id);
    request.database_config_user ()->setChangeNotificationsChecksum ("");
    Database_Logs::log (sendreceive_changes_text () + "Removing notification: " + convert_to_string (id), Filter_Roles::translator ());
  }

  
  // Any identifiers on the server, but not on the client, download them from the server.
  vector <int> download_identifiers = filter_string_array_diff (server_identifiers, client_identifiers);
  for (auto & id : download_identifiers) {
    sendreceive_changes_kick_watchdog ();
    Database_Logs::log (sendreceive_changes_text () + "Downloading notification: " + convert_to_string (id), Filter_Roles::translator ());
    post ["a"] = convert_to_string (Sync_Logic::changes_get_modification);
    post ["i"] = convert_to_string (id);
    response = sync_logic.post (post, url, error);
    if (!error.empty ()) {
      Database_Logs::log (sendreceive_changes_text () + "Failure downloading notification: " + error, Filter_Roles::translator ());
    }
    else {
      // The server has put all bits together, one bit per line.
      vector <string> lines = filter_string_explode (response, '\n');
      string category;
      if (!lines.empty ()) {
        category = lines [0];
        lines.erase (lines.begin ());
      }
      string bible;
      if (!lines.empty ()) {
        bible = lines [0];
        lines.erase (lines.begin ());
      }
      int book = 0;
      if (!lines.empty ()) {
        book = convert_to_int (lines [0]);
        lines.erase (lines.begin ());
      }
      int chapter = 0;
      if (!lines.empty ()) {
        chapter = convert_to_int (lines [0]);
        lines.erase (lines.begin ());
      }
      int verse = 0;
      if (!lines.empty ()) {
        verse = convert_to_int (lines [0]);
        lines.erase (lines.begin ());
      }
      string oldtext;
      if (!lines.empty ()) {
        oldtext = lines [0];
        lines.erase (lines.begin ());
      }
      string modification;
      if (!lines.empty ()) {
        modification = lines [0];
        lines.erase (lines.begin ());
      }
      string newtext;
      if (!lines.empty ()) {
        newtext = lines [0];
        lines.erase (lines.begin ());
      }
      database_modifications.storeClientNotification (id, user, category, bible, book, chapter, verse, oldtext, modification, newtext);
      request.database_config_user ()->setChangeNotificationsChecksum ("");
    }
  }
  

  // Done.
  Database_Logs::log (sendreceive_changes_text () + "Ready", Filter_Roles::translator ());
  send_receive_changes_done ();
}
void WindowShowRelatedVerses::load_webview (const gchar * url)
{
  // New url.
  active_url = url;

  // Start writing a html page.
  HtmlWriter2 htmlwriter ("");
  bool display_another_page = true;

  if (active_url.find ("keyterm ") == 0) {
    item_type = ritKeytermId;
    item_id = active_url.substr (8, 100);
    gtk_button_clicked (GTK_BUTTON (button_item));
    display_another_page = false;
  }

  else if (active_url.find ("strong ") == 0) {
    item_type = ritStrongNumber;
    item_id = active_url.substr (7, 100);
    gtk_button_clicked (GTK_BUTTON (button_item));
    display_another_page = false;
  }

  else if (active_url.find ("parallels") == 0) {
    item_type = ritParallels;
    gtk_button_clicked (GTK_BUTTON (button_item));
    display_another_page = false;
  }

  else {

    // Display the keyterms in the verse, and their renderings.
    htmlwriter.heading_open (3);
    htmlwriter.text_add (_("Keyterms in verse ") + myreference.verse);
    htmlwriter.heading_close ();
    vector <int> keyterms = keyterms_get_terms_in_verse(myreference);
    for (unsigned int i = 0; i < keyterms.size(); i++) {

      htmlwriter.paragraph_open();

      // Display the keyterm.
      ustring term;
      keyterms_get_term(keyterms[i], term);
      htmlwriter.text_add ("* ");
      ustring url = "keyterm " + convert_to_string (keyterms[i]);
      htmlwriter.hyperlink_add (url, term);
      htmlwriter.text_add (": ");

      // Display the renderings.
      vector <ustring> renderings;
      vector <bool> wholewords;
      vector <bool> casesensitives;
      ustring category;
      {
        ustring dummy1;
        vector < Reference > dummy2;
        keyterms_get_data(keyterms[i], category, dummy1, dummy2);
      }
      keyterms_retrieve_renderings(myproject, term, category, renderings, wholewords, casesensitives);
      for (unsigned int i2 = 0; i2 < renderings.size(); i2++) {
        if (i2)
          htmlwriter.text_add (", ");
        htmlwriter.text_add (renderings[i2]);
      }

      htmlwriter.paragraph_close();
    }
    
    // If there are no keyterms, mention this.
    if (keyterms.empty()) {
      htmlwriter.paragraph_open ();
      htmlwriter.text_add ("none");
      htmlwriter.paragraph_close ();
    }

    // Terms derived from the Strong's numbers in this verse.
    htmlwriter.heading_open (3);
    htmlwriter.text_add (_("Similar words in other verses"));
    htmlwriter.heading_close ();

    // Get the data.
    vector <ustring> strongs;
    vector <ustring> words;
    kjv_get_strongs_data (myreference, strongs, words);

    // Display the data.
    for (unsigned int i = 0; i < strongs.size(); i++) {
      htmlwriter.paragraph_open ();
      Parse parse (strongs[i]);
      for (unsigned int i2 = 0; i2 < parse.words.size (); i2++) {
        htmlwriter.text_add (words[i]);
        htmlwriter.text_add (" ");
        ustring url = "strong " + parse.words[i2];
        htmlwriter.hyperlink_add (url, parse.words[i2]);
      }
      htmlwriter.paragraph_close ();
    }
    
    // Parallel passages.
    vector <Reference> parallel_references;
    vector <ustring> parallel_comments;
    parallel_passages_retrieve (myreference, parallel_references, parallel_comments);
    if (!parallel_references.empty()) {
      extern Settings *settings;
      ProjectConfiguration *projectconfig = settings->projectconfig(myproject);
      ustring language = projectconfig->language_get();
      htmlwriter.heading_open (3);
      htmlwriter.text_add (_("Parallel passages"));
      htmlwriter.heading_close ();
      for (unsigned int i = 0; i < parallel_references.size(); i++) {
        htmlwriter.paragraph_open ();
        htmlwriter.text_add (parallel_references[i].human_readable (language) + " " + parallel_comments[i]);
        htmlwriter.paragraph_close ();
      }
      htmlwriter.paragraph_open ();
      htmlwriter.hyperlink_add ("parallels", _("Send to references window"));
      htmlwriter.paragraph_close ();
    }    

  }
  
  htmlwriter.finish();
  if (display_another_page) {
    // Load the page.
    webkit_web_view_load_string (WEBKIT_WEB_VIEW (webview), 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));
    gtk_adjustment_set_value (adjustment, scrolling_position[active_url]);
  }
}
示例#8
0
/* <num> <radix_int> <string> cvrs <substring> */
static int
zcvrs(i_ctx_t *i_ctx_p)
{
    os_ptr op = osp;
    int radix;

    check_type(op[-1], t_integer);
    if (op[-1].value.intval < 2 || op[-1].value.intval > 36)
        return_error(e_rangecheck);
    radix = op[-1].value.intval;
    check_write_type(*op, t_string);
    if (radix == 10) {
        switch (r_type(op - 2)) {
            case t_integer:
            case t_real:
                {
                    int code = convert_to_string(imemory, op - 2, op);

                    if (code < 0)
                        return code;
                    pop(2);
                    return 0;
                }
            case t__invalid:
                return_error(e_stackunderflow);
            default:
                return_error(e_rangecheck); /* CET 24-05 wants rangecheck */
        }
    } else {
        uint ival;
        byte digits[sizeof(ulong) * 8];
        byte *endp = &digits[countof(digits)];
        byte *dp = endp;

        switch (r_type(op - 2)) {
            case t_integer:
                ival = (uint) op[-2].value.intval;
                break;
            case t_real:
                {
                    float fval = op[-2].value.realval;

                    if (!REAL_CAN_BE_INT(fval))
                        return_error(e_rangecheck);
                    ival = (ulong) (long)fval;
                } break;
            case t__invalid:
                return_error(e_stackunderflow);
            default:
                return_error(e_rangecheck); /* CET 24-05 wants rangecheck */
        }
        do {
            int dit = ival % radix;

            *--dp = dit + (dit < 10 ? '0' : ('A' - 10));
            ival /= radix;
        }
        while (ival);
        if (endp - dp > r_size(op))
            return_error(e_rangecheck);
        memcpy(op->value.bytes, dp, (uint) (endp - dp));
        r_set_size(op, endp - dp);
    }
    op[-2] = *op;
    pop(2);
    return 0;
}
示例#9
0
void statistics_statistics ()
{
  Webserver_Request request;
  Database_Mail database_mail = Database_Mail (&request);
  Database_Modifications database_modifications;
  Database_Notes database_notes (&request);
  
  
  Database_Logs::log (translate("Sending statistics"), Filter_Roles::manager ());

  
  string siteUrl = config_logic_site_url ();
  
  
  vector <string> bibles = request.database_bibles()->getBibles ();
  
  
  vector <string> users = request.database_users ()->getUsers ();
  for (auto & user : users) {
    
    
    string subject = "Bibledit " + translate("statistics");
    vector <string> body;
    
    
    if (request.database_config_user()->getUserPendingChangesNotification (user)) {
      vector <int> ids = database_modifications.getNotificationIdentifiers (user);
      body.push_back ("<p><a href=\"" + siteUrl + changes_changes_url () + "\">" + translate("Number of change notifications") + "</a>: " + convert_to_string (ids.size()) + "</p>\n");
    }
    
    
    if (request.database_config_user()->getUserAssignedNotesStatisticsNotification (user)) {
      vector <int> ids = database_notes.selectNotes (
                                                     bibles, // Bibles.
                                                     0,      // Book
                                                     0,      // Chapter
                                                     0,      // Verse
                                                     3,      // Passage selector.
                                                     0,      // Edit selector.
                                                     0,      // Non-edit selector.
                                                     "",     // Status selector.
                                                     "",     // Bible selector.
                                                     user,   // Assignment selector.
                                                     0,      // Subscription selector.
                                                     -1,     // Severity selector.
                                                     0,      // Text selector.
                                                     "",     // Search text.
                                                     -1);     // Limit.
      body.push_back ("<p><a href=\"" + siteUrl + notes_index_url () + "?presetselection=assigned\">" + translate("Number of consultation notes assigned to you awaiting your response") + "</a>: " + convert_to_string (ids.size ()) + "</p>\n");
    }
    
    
    if (request.database_config_user()->getUserSubscribedNotesStatisticsNotification (user)) {
      body.push_back ("<p>" + translate("Number of consultation notes you are subscribed to") + ":</p>\n");
      body.push_back ("<ul>\n");
      request.session_logic ()->setUsername (user);
      
      vector <int> ids = database_notes.selectNotes (
                                                     bibles, // Bible.
                                                     0,      // Book
                                                     0,      // Chapter
                                                     0,      // Verse
                                                     3,      // Passage selector.
                                                     0,      // Edit selector.
                                                     0,      // Non-edit selector.
                                                     "",     // Status selector.
                                                     "",     // Bible selector.
                                                     "",     // Assignment selector.
                                                     1,      // Subscription selector.
                                                     -1,     // Severity selector.
                                                     0,      // Text selector.
                                                     "",     // Search text.
                                                     -1);     // Limit.
      body.push_back ("<li><a href=\"" + siteUrl + notes_index_url () + "?presetselection=subscribed\">" + translate("Total") + "</a>: " + convert_to_string (ids.size ()) + "</li>\n");
      ids = database_notes.selectNotes (
                                                     bibles, // Bible.
                                                     0,      // Book
                                                     0,      // Chapter
                                                     0,      // Verse
                                                     3,      // Passage selector.
                                                     0,      // Edit selector.
                                                     1,      // Non-edit selector.
                                                     "",     // Status selector.
                                                     "",     // Bible selector.
                                                     "",     // Assignment selector.
                                                     1,      // Subscription selector.
                                                     -1,     // Severity selector.
                                                     0,      // Text selector.
                                                     "",     // Search text.
                                                     -1);     // Limit.
      body.push_back ("<li><a href=\"" + siteUrl + notes_index_url () + "?presetselection=subscribeddayidle\">" + translate("Inactive for a day") + "</a>: " + convert_to_string (ids.size ()) + "</li>\n");
      ids = database_notes.selectNotes (
                                                     bibles, // Bible.
                                                     0,      // Book
                                                     0,      // Chapter
                                                     0,      // Verse
                                                     3,      // Passage selector.
                                                     0,      // Edit selector.
                                                     3,      // Non-edit selector.
                                                     "",     // Status selector.
                                                     "",     // Bible selector.
                                                     "",     // Assignment selector.
                                                     1,      // Subscription selector.
                                                     -1,     // Severity selector.
                                                     0,      // Text selector.
                                                     "",     // Search text.
                                                     -1);     // Limit.
      body.push_back ("<li><a href=\"" + siteUrl + notes_index_url () + "?presetselection=subscribedweekidle\">" + translate("Inactive for a week") + "</a>: " + convert_to_string (ids.size ()) + "</li>\n");
      body.push_back ("</ul>\n");
      request.session_logic ()->setUsername ("");
    }
    
    
    if (!body.empty ()) {
      string mailbody = filter_string_implode (body, "\n");
      database_mail.send (user, subject, mailbody);
    }
  }
}
示例#10
0
文件: main.cpp 项目: rdevon/DBN
int main (int argc, char * argv[])
{
   
   std::streambuf *psbuf = NULL;
   std::ofstream log_stream;
   std::streambuf *pStreambuf = std::cout.rdbuf();
   
   //--------------RNG INIT STUFF
   srand((unsigned)time(0));
   long seed;
   r = gsl_rng_alloc (gsl_rng_rand48);     // pick random number generator
   seed = time (NULL) * getpid();
   gsl_rng_set (r, seed);                  // set seed
   // TESTING AREA
   
   //---------------
   DBN *dbn;
   
   if (command_option_exists(argv, argv+argc, "-n")) {
      dbn = return_network();
      std::cout << dbn << std::endl;
      std::cout << "Ready to learn" << std::endl;
      std::cout << "If you are using visualization:" << std::endl;
      std::cout << "'V': pauses visualization" << std::endl;
      std::cout << "<SPACE>: pauses learning" << std::endl;
      std::cout << "'+'/'-' increases/decreases learning rate" << std::endl;
      std::cout << "'['/']' increases/decreases output threshold" << std::endl;
      std::cout << "'L' stops learning for layer (skips to next if any)" << std::endl;
      std::cout << "Current visualization is the features displayed on top with the plot of the reconstruction cost in the box (gl text not supported yet)" << std::endl;
      std::cout << "Press <ENTER> to start learning: ";
      std::cin.get();
   }
   else if (command_option_exists(argv, argv+argc, "-l")) {
      std::string filename = get_command_line(argv, argv+argc, "-l");
      MLP mlp = load_MLP(filename);
      dbn = new DBN(mlp);
      dbn->data_layers.clear();
      dbn->view();
      exit(EXIT_SUCCESS);
   }
   else if (command_option_exists(argv, argv+argc, "-f")) {
      if (argc != 3) {
         print_usage();
         exit(EXIT_FAILURE);
      }
      //Initialization, time, logfile stuff, etc.
      time_t t = time(0);   // get time now
      struct tm * the_time = localtime( & t );
      mkdir(out_path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
      out_path += convert_to_string(*the_time) + "/";
      mkdir((out_path).c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
      
      std::string filename = get_command_line(argv, argv+argc, "-f");
      dbn = return_aod_network(filename, log_stream, psbuf);
      
   }
   else if (command_option_exists(argv, argv+argc, "-F")) {
      
      std::string filename = get_command_line(argv, argv+argc, "-F");
      MLP mlp = load_MLP(filename); 
      Autoencoder ae(mlp);
      ae.name = (mlp).name + "fine_tuning";
      Gradient_Descent gd(0);
      gd.teachAE(ae);
      MLP ae_mlp;
      save(ae);
      exit(EXIT_SUCCESS);
   }
   else if (command_option_exists(argv, argv+argc, "-stack")) {
      std::string filename = get_command_line(argv, argv+argc, "-stack");
      dbn = load_and_stack(filename, log_stream, psbuf);
   }
   else {
      print_usage();
      exit(EXIT_SUCCESS);
   }
   ContrastiveDivergence cd(1000);
   dbn->learn(cd);
   std::cout.rdbuf(pStreambuf);
   log_stream.close();
   exit(1);
   return 0;
}
示例#11
0
string search_strong (void * webserver_request)
{
  Webserver_Request * request = (Webserver_Request *) webserver_request;


  Database_Kjv database_kjv = Database_Kjv ();
  
  
  string bible = request->database_config_user()->getBible ();
  if (request->query.count ("b")) {
    bible = request->query ["b"];
  }
  
  
  if (request->query.count ("load")) {

    int book = Ipc_Focus::getBook (request);
    int chapter = Ipc_Focus::getChapter (request);
    int verse = Ipc_Focus::getVerse (request);
    
    // Get Strong's numbers, plus English snippets.
    string html = "<table>\n";
    vector <Database_Kjv_Item> details = database_kjv.getVerse (book, chapter, verse);
    for (auto & detail : details) {
      string strong = detail.strong;
      string english = detail.english;
      html += "<tr><td><a href=\"" + strong + "\">" + strong + "</a></td><td>" + english + "</td></tr>\n";
    }
    html += "</table>\n";
    
    return html;
  }
  
  
  if (request->query.count ("strong")) {
    
    string strong = request->query ["strong"];
    strong = filter_string_trim (strong);
    
    vector <int> passages;
    
    vector <Passage> details = database_kjv.searchStrong (strong);
    
    for (auto & passage : details) {
      int i_passage = filter_passage_to_integer (passage);
      passages.push_back (i_passage);
    }
    
    passages = array_unique (passages);
    sort (passages.begin(), passages.end());
    
    string output;
    for (auto & passage : passages) {
      if (!output.empty()) output.append ("\n");
      output.append (convert_to_string (passage));
    }
    return output;
  }
  
  
  if (request->query.count ("id")) {
    int id = convert_to_int (request->query ["id"]);
    
    // Get the and passage for this identifier.
    Passage passage = filter_integer_to_passage (id);
    int book = passage.book;
    int chapter = passage.chapter;
    string verse = passage.verse;
    
    // Get the plain text.
    string text = search_logic_get_bible_verse_text (bible, book, chapter, convert_to_int (verse));
    
    // Format it.
    string link = filter_passage_link_for_opening_editor_at (book, chapter, verse);
    string output = "<div>" + link + " " + text + "</div>";
    
    // Output to browser.
    return output;
  }
  
  
  string page;
  
  Assets_Header header = Assets_Header (translate("Search"), request);
  header.setNavigator ();
  header.addBreadCrumb (menu_logic_search_menu (), menu_logic_search_text ());
  page = header.run ();
  
  Assets_View view;
  
  view.set_variable ("bible", bible);
  
  string script = "var searchBible = \"" + bible + "\";";
  view.set_variable ("script", script);

  page += view.render ("search", "strong");
  
  page += Assets_Page::footer ();
  
  return page;
}
示例#12
0
/**
 * Decrypts an encrypted text
 *
 *<code>
 *	echo $crypt->decrypt($encrypted, "decrypt password");
 *</code>
 *
 * @param string $text
 * @param string $key
 * @return string
 */
PHP_METHOD(Phalcon_Crypt, decrypt){

	zval *text, *key = NULL, *decrypt_key = NULL, *cipher, *mode, *iv_size = NULL;
	zval *key_size, *text_size, *iv, *text_to_decipher, *decrypted = NULL;
	zval *padding_type, *block_size = NULL;
	zval *handler, *arguments = NULL, *value = NULL;

	PHALCON_MM_GROW();

	phalcon_fetch_params(1, 1, 1, &text, &key);

	if (phalcon_function_exists_ex(SS("mcrypt_get_iv_size") TSRMLS_CC) == FAILURE) {
		PHALCON_THROW_EXCEPTION_STR(phalcon_crypt_exception_ce, "mcrypt extension is required");
		return;
	}

	PHALCON_OBS_VAR(handler);
	phalcon_read_property_this(&handler, this_ptr, SL("_beforeDecrypt"), PH_NOISY TSRMLS_CC);

	if (phalcon_is_callable(handler TSRMLS_CC)) {
		PHALCON_SEPARATE_PARAM(text);

		PHALCON_INIT_NVAR(arguments);
		array_init_size(arguments, 1);
		phalcon_array_append(&arguments, text, 0);

		PHALCON_INIT_NVAR(value);
		PHALCON_CALL_USER_FUNC_ARRAY(value, handler, arguments);

		PHALCON_CPY_WRT(text, value);
	}

	if (!key || Z_TYPE_P(key) == IS_NULL) {
		decrypt_key = phalcon_fetch_nproperty_this(this_ptr, SL("_key"), PH_NOISY TSRMLS_CC);
	} else {
		decrypt_key = key;
	}

	if (PHALCON_IS_EMPTY(decrypt_key)) {
		PHALCON_THROW_EXCEPTION_STR(phalcon_crypt_exception_ce, "Decryption key cannot be empty");
		return;
	}

	cipher = phalcon_fetch_nproperty_this(this_ptr, SL("_cipher"), PH_NOISY TSRMLS_CC);
	mode   = phalcon_fetch_nproperty_this(this_ptr, SL("_mode"), PH_NOISY TSRMLS_CC);

	PHALCON_CALL_FUNCTION(&iv_size, "mcrypt_get_iv_size", cipher, mode);
	if (unlikely(Z_TYPE_P(iv_size) != IS_LONG)) {
		convert_to_long(iv_size);
	}

	PHALCON_INIT_VAR(key_size);
	phalcon_fast_strlen(key_size, decrypt_key);
	if (PHALCON_GT(key_size, iv_size)) {
		PHALCON_THROW_EXCEPTION_STR(phalcon_crypt_exception_ce, "Size of key is too large for this algorithm");
		return;
	}

	PHALCON_INIT_VAR(text_size);
	phalcon_fast_strlen(text_size, text);
	if (PHALCON_GT(key_size, text_size)) {
		PHALCON_THROW_EXCEPTION_STR(phalcon_crypt_exception_ce, "Size of IV is larger than text to decrypt");
		return;
	}

	PHALCON_INIT_VAR(iv);
	phalcon_substr(iv, text, 0, Z_LVAL_P(iv_size));

	PHALCON_INIT_VAR(text_to_decipher);
	phalcon_substr(text_to_decipher, text, Z_LVAL_P(iv_size), 0);

	PHALCON_CALL_FUNCTION(&decrypted, "mcrypt_decrypt", cipher, decrypt_key, text_to_decipher, mode, iv);
	if (unlikely(Z_TYPE_P(decrypted) != IS_STRING)) {
		convert_to_string(decrypted);
	}

	PHALCON_CALL_FUNCTION(&block_size, "mcrypt_get_block_size", cipher, mode);
	if (unlikely(Z_TYPE_P(block_size) != IS_LONG)) {
		convert_to_long(block_size);
	}

	padding_type = phalcon_fetch_nproperty_this(this_ptr, SL("_padding"), PH_NOISY TSRMLS_CC);

	assert(Z_TYPE_P(padding_type) == IS_LONG);
	assert(Z_TYPE_P(block_size) == IS_LONG);
	assert(Z_TYPE_P(mode) == IS_STRING);
	assert(Z_TYPE_P(decrypted) == IS_STRING);

	phalcon_crypt_unpad_text(return_value, decrypted, mode, Z_LVAL_P(block_size), Z_LVAL_P(padding_type) TSRMLS_CC);

	PHALCON_OBS_NVAR(handler);
	phalcon_read_property_this(&handler, this_ptr, SL("_afterDecrypt"), PH_NOISY TSRMLS_CC);

	if (phalcon_is_callable(handler TSRMLS_CC)) {
		PHALCON_INIT_NVAR(arguments);
		array_init_size(arguments, 1);
		phalcon_array_append(&arguments, return_value, 0);

		PHALCON_INIT_NVAR(value);
		PHALCON_CALL_USER_FUNC_ARRAY(value, handler, arguments);

		RETURN_CTOR(value);
	}

	RETURN_MM();
}
示例#13
0
/**
 * Encrypts a text
 *
 *<code>
 *	$encrypted = $crypt->encrypt("Ultra-secret text", "encrypt password");
 *</code>
 *
 * @param string $text
 * @param string $key
 * @return string
 */
PHP_METHOD(Phalcon_Crypt, encrypt){

	zval *source, *text, *key = NULL, *encrypt_key = NULL, *cipher, *mode, *padding_type, *iv_size = NULL;
	zval *rand, *iv = NULL, *encrypt = NULL, *block_size = NULL, *padded;
	zval *handler, *arguments = NULL, *value = NULL;

	PHALCON_MM_GROW();

	phalcon_fetch_params(1, 1, 1, &source, &key);

	PHALCON_OBS_VAR(handler);
	phalcon_read_property_this(&handler, this_ptr, SL("_beforeEncrypt"), PH_NOISY TSRMLS_CC);

	if (phalcon_is_callable(handler TSRMLS_CC)) {
		PHALCON_SEPARATE_PARAM(source);

		PHALCON_INIT_NVAR(arguments);
		array_init_size(arguments, 1);
		phalcon_array_append(&arguments, source, 0);

		PHALCON_INIT_NVAR(value);
		PHALCON_CALL_USER_FUNC_ARRAY(value, handler, arguments);

		PHALCON_CPY_WRT(source, value);
	}

	/* Do not use make_printable_zval() here: we need the conversion with type juggling */
	if (Z_TYPE_P(source) != IS_STRING) {
		PHALCON_INIT_VAR(text);
		phalcon_cast(text, source, IS_STRING);
	}
	else {
		text = source;
	}

	if (phalcon_function_exists_ex(SS("mcrypt_get_iv_size") TSRMLS_CC) == FAILURE) {
		PHALCON_THROW_EXCEPTION_STR(phalcon_crypt_exception_ce, "mcrypt extension is required");
		return;
	}

	if (!key || Z_TYPE_P(key) == IS_NULL) {
		encrypt_key = phalcon_fetch_nproperty_this(this_ptr, SL("_key"), PH_NOISY TSRMLS_CC);
	} else {
		PHALCON_CPY_WRT_CTOR(encrypt_key, key);
		if (Z_TYPE_P(encrypt_key) != IS_STRING) {
			convert_to_string(encrypt_key);
		}
	}

	if (PHALCON_IS_EMPTY(encrypt_key)) {
		PHALCON_THROW_EXCEPTION_STR(phalcon_crypt_exception_ce, "Encryption key cannot be empty");
		return;
	}

	cipher = phalcon_fetch_nproperty_this(this_ptr, SL("_cipher"), PH_NOISY TSRMLS_CC);
	mode   = phalcon_fetch_nproperty_this(this_ptr, SL("_mode"), PH_NOISY TSRMLS_CC);

	PHALCON_CALL_FUNCTION(&iv_size, "mcrypt_get_iv_size", cipher, mode);
	if (unlikely(Z_TYPE_P(iv_size) != IS_LONG)) {
		convert_to_long(iv_size);
	}

	if (Z_STRLEN_P(encrypt_key) > Z_LVAL_P(iv_size)) {
		PHALCON_THROW_EXCEPTION_STR(phalcon_crypt_exception_ce, "Size of key is too large for this algorithm");
		return;
	}

	PHALCON_INIT_VAR(rand);
	ZVAL_LONG(rand, 2);

	PHALCON_CALL_FUNCTION(&iv, "mcrypt_create_iv", iv_size, rand);
	if (unlikely(Z_TYPE_P(iv) != IS_STRING)) {
		convert_to_string(iv);
	}

	PHALCON_CALL_FUNCTION(&block_size, "mcrypt_get_block_size", cipher, mode);
	if (unlikely(Z_TYPE_P(block_size) != IS_LONG)) {
		convert_to_long(block_size);
	}

	padding_type = phalcon_fetch_nproperty_this(this_ptr, SL("_padding"), PH_NOISY TSRMLS_CC);

	assert(Z_TYPE_P(padding_type) == IS_LONG);
	assert(Z_TYPE_P(block_size) == IS_LONG);
	assert(Z_TYPE_P(mode) == IS_STRING);
	assert(Z_TYPE_P(text) == IS_STRING);

	PHALCON_INIT_VAR(padded);
	phalcon_crypt_pad_text(padded, text, mode, Z_LVAL_P(block_size), Z_LVAL_P(padding_type) TSRMLS_CC);
	assert(Z_TYPE_P(padded) == IS_STRING);

	PHALCON_CALL_FUNCTION(&encrypt, "mcrypt_encrypt", cipher, encrypt_key, padded, mode, iv);

	PHALCON_CONCAT_VV(return_value, iv, encrypt);

	PHALCON_OBS_NVAR(handler);
	phalcon_read_property_this(&handler, this_ptr, SL("_afterEncrypt"), PH_NOISY TSRMLS_CC);

	if (phalcon_is_callable(handler TSRMLS_CC)) {
		PHALCON_INIT_NVAR(arguments);
		array_init_size(arguments, 1);
		phalcon_array_append(&arguments, return_value, 0);

		PHALCON_INIT_NVAR(value);
		PHALCON_CALL_USER_FUNC_ARRAY(value, handler, arguments);

		RETURN_CTOR(value);
	}

	RETURN_MM();
}
示例#14
0
static void call_php(char *name, PARAMDSC *r, int argc, PARAMDSC **argv)
{
	do {
		zval callback, args[4], return_value;
		PARAMVARY *res = (PARAMVARY*)r->dsc_address;
		int i;

		ZVAL_STRING(&callback, name);

		LOCK();

		/* check if the requested function exists */
		if (!zend_is_callable(&callback, 0, NULL)) {
			break;
		}

		UNLOCK();

		/* create the argument array */
		for (i = 0; i < argc; ++i) {

			/* test arg for null */
			if (argv[i]->dsc_flags & DSC_null) {
				ZVAL_NULL(&args[i]);
				continue;
			}

			switch (argv[i]->dsc_dtype) {
				ISC_INT64 l;
				struct tm t;
				char const *fmt;
				char d[64];

				case dtype_cstring:
//???
					ZVAL_STRING(&args[i], (char*)argv[i]->dsc_address);
					break;

				case dtype_text:
//???
					ZVAL_STRINGL(&args[i], (char*)argv[i]->dsc_address, argv[i]->dsc_length);
					break;

				case dtype_varying:
//???
					ZVAL_STRINGL(&args[i], ((PARAMVARY*)argv[i]->dsc_address)->vary_string,
						((PARAMVARY*)argv[i]->dsc_address)->vary_length);
					break;

				case dtype_short:
					if (argv[i]->dsc_scale == 0) {
						ZVAL_LONG(&args[i], *(short*)argv[i]->dsc_address);
					} else {
						ZVAL_DOUBLE(&args[i],
							((double)*(short*)argv[i]->dsc_address)/scales[-argv[i]->dsc_scale]);
					}
					break;

				case dtype_long:
					if (argv[i]->dsc_scale == 0) {
						ZVAL_LONG(&args[i], *(ISC_LONG*)argv[i]->dsc_address);
					} else {
						ZVAL_DOUBLE(&args[i],
							((double)*(ISC_LONG*)argv[i]->dsc_address)/scales[-argv[i]->dsc_scale]);
					}
					break;

				case dtype_int64:
					l = *(ISC_INT64*)argv[i]->dsc_address;

					if (argv[i]->dsc_scale == 0 && l <= LONG_MAX && l >= LONG_MIN) {
						ZVAL_LONG(&args[i], (long)l);
					} else {
						ZVAL_DOUBLE(&args[i], ((double)l)/scales[-argv[i]->dsc_scale]);
					}
					break;

				case dtype_real:
					ZVAL_DOUBLE(&args[i], *(float*)argv[i]->dsc_address);
					break;

				case dtype_double:
					ZVAL_DOUBLE(&args[i], *(double*)argv[i]->dsc_address);
					break;

				case dtype_sql_date:
					isc_decode_sql_date((ISC_DATE*)argv[i]->dsc_address, &t);
					ZVAL_STRINGL(&args[i], d, strftime(d, sizeof(d), INI_STR("ibase.dateformat"), &t),1);
					break;

				case dtype_sql_time:
					isc_decode_sql_time((ISC_TIME*)argv[i]->dsc_address, &t);
					ZVAL_STRINGL(&args[i], d, strftime(d, sizeof(d), INI_STR("ibase.timeformat"), &t),1);
					break;

				case dtype_timestamp:
					isc_decode_timestamp((ISC_TIMESTAMP*)argv[i]->dsc_address, &t);
					ZVAL_STRINGL(&args[i], d, strftime(d, sizeof(d), INI_STR("ibase.timestampformat"), &t));
					break;
			}
		}

		LOCK();

		/* now call the function */
		if (FAILURE == call_user_function(EG(function_table), NULL,
				&callback, &return_value, argc, args)) {
			UNLOCK();
			break;
		}

		UNLOCK();

		for (i = 0; i < argc; ++i) {
			switch (argv[i]->dsc_dtype) {
				case dtype_sql_date:
				case dtype_sql_time:
				case dtype_timestamp:
					zval_dtor(&args[i]);
			}
		}

		zval_dtor(&callback);

		/* return whatever type we got back from the callback: let DB handle conversion */
		switch (Z_TYPE(return_value)) {

			case IS_LONG:
				r->dsc_dtype = dtype_long;
				*(long*)r->dsc_address = Z_LVAL(return_value);
				r->dsc_length = sizeof(long);
				break;

			case IS_DOUBLE:
				r->dsc_dtype = dtype_double;
				*(double*)r->dsc_address = Z_DVAL(return_value);
				r->dsc_length = sizeof(double);
				break;

			case IS_NULL:
				r->dsc_flags |= DSC_null;
				break;

			default:
				convert_to_string(&return_value);

			case IS_STRING:
				r->dsc_dtype = dtype_varying;
				memcpy(res->vary_string, Z_STRVAL(return_value),
					(res->vary_length = min(r->dsc_length-2,Z_STRLEN(return_value))));
				r->dsc_length = res->vary_length+2;
				break;
		}

		zval_dtor(&return_value);

		return;

	} while (0);

	/**
	* If we end up here, we should report an error back to the DB engine, but
	* that's not possible. We can however report it back to PHP.
	*/
	LOCK();
	php_error_docref(NULL, E_WARNING, "Error calling function '%s' from database", name);
	UNLOCK();
}
示例#15
0
文件: text.c 项目: Myleft/cphalcon
/**
 * Returns human readable sizes
 *
 * @param int $size
 * @param string $forceUnit
 * @param string $format
 * @param boolean $si
 * @return string
 */
PHP_METHOD(Phalcon_Text, bytes){

	zval *z_size, *z_force_unit = NULL, *format = NULL, *si = NULL;
	char *force_unit;
	const char **units;
	const char *units1[] = {"B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"};
	const char *units2[] = {"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"};
	double size;
	int mod, power = 0, found = 0, i, j = 0;

	PHALCON_MM_GROW();

	phalcon_fetch_params(1, 1, 3, &z_size, &z_force_unit, &format, &si);

	PHALCON_SEPARATE_PARAM(z_size);
	convert_to_double(z_size);

	size = Z_DVAL_P(z_size);

	if (!z_force_unit) {
		PHALCON_INIT_VAR(z_force_unit);
	} else {
		PHALCON_SEPARATE_PARAM(z_force_unit);
		convert_to_string(z_force_unit);
	}

	if (!format) {
		PHALCON_INIT_VAR(format);
	} else {
		PHALCON_SEPARATE_PARAM(format);
		convert_to_string(format);
	}
		
	if (PHALCON_IS_EMPTY(format)) {
		PHALCON_INIT_NVAR(format);
		ZVAL_STRING(format, "%01.2f %s", 1);
	}

	if (!si) {
		si = PHALCON_GLOBAL(z_true);
	}

	if (!zend_is_true(si) || (!PHALCON_IS_EMPTY(z_force_unit) && phalcon_memnstr_str(z_force_unit, SL("i")))) {
		units = units2;
		mod = 1024;
	} else {
		units = units1;
		mod = 1000;
	}

	if (!PHALCON_IS_EMPTY(z_force_unit)) {
		force_unit = Z_STRVAL_P(z_force_unit);
		for (i = 0; i < sizeof(units); i++)
		{
			if (strcasecmp(force_unit, units[i]) == 0) {
				found = 1;
				power = i;
				break;
			}
		}
	}

	if (found) {
		while(j < power) {
			size /= mod;
			j++;
		}
	} else {
		while(size > mod) {
			size /= mod;
			power++;
		}
	}

	PHALCON_INIT_NVAR(z_size);
	ZVAL_DOUBLE(z_size, size);

	PHALCON_INIT_NVAR(z_force_unit);
	ZVAL_STRING(z_force_unit, units[power], 1);

	PHALCON_RETURN_CALL_FUNCTION("sprintf", format, z_size, z_force_unit);

	RETURN_MM();
}
示例#16
0
void DisplayChangesGui::display(const vector <ustring>& differences)
{
  // Store position of scrollled window.
  GtkAdjustment * adjustment = gtk_scrolled_window_get_vadjustment (GTK_SCROLLED_WINDOW (scrolledwindow));
  int scrollbar_position = gtk_adjustment_get_value (adjustment);

  // Variable for holding the number of modifications.
  unsigned int modification_count = 0;

  // Temporally removing the view from the buffer speeds loading text up a huge lot.
  g_object_ref(textbuffer);
  gtk_text_view_set_buffer(GTK_TEXT_VIEW(textview), NULL);
  
  // Clear buffer.
  clear();

  // Load text.
  for (unsigned int i = 0; i < differences.size(); i++) {
    GtkTextIter iter;
    GtkTextTag *tag = NULL;
    ustring line = differences[i];
    while (!line.empty()) {
      // Handle insertion or deletion flag for the next character.
      tag = NULL;
      ustring character = line.substr (0, 1);
      if (!strcmp (character.c_str(), INSERTION_FLAG)) {
        tag = heavy_weight_tag;
      }
      if (!strcmp (character.c_str(), DELETION_FLAG)) {
        tag = strike_through_tag;
      }
      if (tag) {
        line.erase (0, 1);
        // Another modification.
        modification_count++;
      }
      // Print one character with optional markup.
      character = line.substr (0, 1);
      gtk_text_buffer_get_end_iter(textbuffer, &iter);
      gtk_text_buffer_insert_with_tags(textbuffer, &iter, character.c_str(), -1, tag, NULL);
      line.erase(0, 1);
    }
    // End of line.
    gtk_text_buffer_get_end_iter(textbuffer, &iter);
    gtk_text_buffer_insert(textbuffer, &iter, "\n", 1);
  }
  
  // Reconnect the view to the buffer.
  gtk_text_view_set_buffer(GTK_TEXT_VIEW(textview), textbuffer);
  g_object_unref(textbuffer);
  
  // Show modification count.
  ustring message = _("Number of modifications: ");
  message.append (convert_to_string (modification_count));
  gtk_label_set_text (GTK_LABEL (label), message.c_str());
  
  // Restore scrollled window's position.
  // The window will then show the same block of text as before loading. This makes editing the text easier.
  while (gtk_events_pending())
    gtk_main_iteration();
  gtk_scrolled_window_get_vadjustment (GTK_SCROLLED_WINDOW (scrolledwindow));
  gtk_adjustment_set_value (adjustment, scrollbar_position);
}
示例#17
0
static PHP_METHOD(swoole_server_port, set)
{
    zval *zset = NULL;
    HashTable *vht;
    zval *v;

    if (zend_parse_parameters(ZEND_NUM_ARGS()TSRMLS_CC, "z", &zset) == FAILURE)
    {
        return;
    }

    vht = Z_ARRVAL_P(zset);
    swListenPort *port = swoole_get_object(getThis());
    swoole_server_port_property *property = swoole_get_property(getThis(), 0);

    if (port == NULL || property == NULL)
    {
        swoole_php_fatal_error(E_ERROR, "Please use the swoole_server->listen method.");
        return;
    }

    property->setting = zset;

    //backlog
    if (php_swoole_array_get_value(vht, "backlog", v))
    {
        convert_to_long(v);
        port->backlog = (int) Z_LVAL_P(v);
    }
    //tcp_nodelay
    if (php_swoole_array_get_value(vht, "open_tcp_nodelay", v))
    {
        convert_to_boolean(v);
        port->open_tcp_nodelay = Z_BVAL_P(v);
    }
    //tcp_defer_accept
    if (php_swoole_array_get_value(vht, "tcp_defer_accept", v))
    {
        convert_to_long(v);
        port->tcp_defer_accept = (uint8_t) Z_LVAL_P(v);
    }
    //tcp_keepalive
    if (php_swoole_array_get_value(vht, "open_tcp_keepalive", v))
    {
        convert_to_boolean(v);
        port->open_tcp_keepalive = Z_BVAL_P(v);
    }
    //buffer: split package with eof
    if (php_swoole_array_get_value(vht, "open_eof_split", v))
    {
        convert_to_boolean(v);
        port->protocol.split_by_eof = Z_BVAL_P(v);
        if (port->protocol.split_by_eof)
        {
            port->open_eof_check = 1;
        }
    }
    //package eof
    if (php_swoole_array_get_value(vht, "package_eof", v))
    {
        convert_to_string(v);
        port->protocol.package_eof_len = Z_STRLEN_P(v);
        if (port->protocol.package_eof_len > SW_DATA_EOF_MAXLEN)
        {
            swoole_php_fatal_error(E_ERROR, "pacakge_eof max length is %d", SW_DATA_EOF_MAXLEN);
            RETURN_FALSE;
        }
        bzero(port->protocol.package_eof, SW_DATA_EOF_MAXLEN);
        memcpy(port->protocol.package_eof, Z_STRVAL_P(v), Z_STRLEN_P(v));
    }
    //http_protocol
    if (php_swoole_array_get_value(vht, "open_http_protocol", v))
    {
        convert_to_boolean(v);
        port->open_http_protocol = Z_BVAL_P(v);
    }
    //websocket protocol
    if (php_swoole_array_get_value(vht, "open_websocket_protocol", v))
    {
        convert_to_boolean(v);
        port->open_websocket_protocol = Z_BVAL_P(v);
    }
#ifdef SW_USE_HTTP2
    //http2 protocol
    if (php_swoole_array_get_value(vht, "open_http2_protocol", v))
    {
        convert_to_boolean(v);
        port->open_http2_protocol = Z_BVAL_P(v);
    }
#endif
    //buffer: mqtt protocol
    if (php_swoole_array_get_value(vht, "open_mqtt_protocol", v))
    {
        convert_to_boolean(v);
        port->open_mqtt_protocol = Z_BVAL_P(v);
    }
    //tcp_keepidle
    if (php_swoole_array_get_value(vht, "tcp_keepidle", v))
    {
        convert_to_long(v);
        port->tcp_keepidle = (uint16_t) Z_LVAL_P(v);
    }
    //tcp_keepinterval
    if (php_swoole_array_get_value(vht, "tcp_keepinterval", v))
    {
        convert_to_long(v);
        port->tcp_keepinterval = (uint16_t) Z_LVAL_P(v);
    }
    //tcp_keepcount
    if (sw_zend_hash_find(vht, ZEND_STRS("tcp_keepcount"), (void **) &v) == SUCCESS)
    {
        convert_to_long(v);
        port->tcp_keepcount = (uint16_t) Z_LVAL_P(v);
    }
    //open length check
    if (php_swoole_array_get_value(vht, "open_length_check", v))
    {
        convert_to_boolean(v);
        port->open_length_check = Z_BVAL_P(v);
    }
    //package length size
    if (php_swoole_array_get_value(vht, "package_length_type", v))
    {
        convert_to_string(v);
        port->protocol.package_length_type = Z_STRVAL_P(v)[0];
        port->protocol.package_length_size = swoole_type_size(port->protocol.package_length_type);

        if (port->protocol.package_length_size == 0)
        {
            swoole_php_fatal_error(E_ERROR, "unknow package_length_type, see pack(). Link: http://php.net/pack");
            RETURN_FALSE;
        }
    }
    //package length offset
    if (php_swoole_array_get_value(vht, "package_length_offset", v))
    {
        convert_to_long(v);
        port->protocol.package_length_offset = (int) Z_LVAL_P(v);
    }
    //package body start
    if (php_swoole_array_get_value(vht, "package_body_offset", v) || php_swoole_array_get_value(vht, "package_body_start", v))
    {
        convert_to_long(v);
        port->protocol.package_body_offset = (int) Z_LVAL_P(v);
    }
    /**
     * package max length
     */
    if (php_swoole_array_get_value(vht, "package_max_length", v))
    {
        convert_to_long(v);
        port->protocol.package_max_length = (int) Z_LVAL_P(v);
    }
    /**
     * swoole_packet_mode
     */
    if (SwooleG.serv->packet_mode == 1)
    {
        port->protocol.package_max_length = 64 * 1024 * 1024;
        port->open_length_check = 1;
        port->protocol.package_length_offset = 0;
        port->protocol.package_body_offset = 4;
        port->protocol.package_length_type = 'N';
        port->open_eof_check = 0;
    }

#ifdef SW_USE_OPENSSL
    if (port->ssl)
    {
        if (php_swoole_array_get_value(vht, "ssl_cert_file", v))
        {
            convert_to_string(v);
            if (access(Z_STRVAL_P(v), R_OK) < 0)
            {
                swoole_php_fatal_error(E_ERROR, "ssl cert file[%s] not found.", Z_STRVAL_P(v));
                return;
            }
            port->ssl_cert_file = strdup(Z_STRVAL_P(v));
            port->open_ssl_encrypt = 1;
        }
        if (php_swoole_array_get_value(vht, "ssl_key_file", v))
        {
            convert_to_string(v);
            if (access(Z_STRVAL_P(v), R_OK) < 0)
            {
                swoole_php_fatal_error(E_ERROR, "ssl key file[%s] not found.", Z_STRVAL_P(v));
                return;
            }
            port->ssl_key_file = strdup(Z_STRVAL_P(v));
        }
        if (php_swoole_array_get_value(vht, "ssl_method", v))
        {
            convert_to_long(v);
            port->ssl_method = (int) Z_LVAL_P(v);
        }
        //verify client cert
        if (php_swoole_array_get_value(vht, "ssl_client_cert_file", v))
        {
            convert_to_string(v);
            if (access(Z_STRVAL_P(v), R_OK) < 0)
            {
                swoole_php_fatal_error(E_ERROR, "ssl cert file[%s] not found.", port->ssl_cert_file);
                return;
            }
            port->ssl_client_cert_file = strdup(Z_STRVAL_P(v));
        }
        if (php_swoole_array_get_value(vht, "ssl_verify_depth", v))
        {
            convert_to_long(v);
            port->ssl_verify_depth = (int) Z_LVAL_P(v);
        }
        if (port->open_ssl_encrypt && !port->ssl_key_file)
        {
            swoole_php_fatal_error(E_ERROR, "ssl require key file.");
            return;
        }
        if (php_swoole_array_get_value(vht, "ssl_prefer_server_ciphers", v))
        {
            convert_to_boolean(v);
            port->ssl_config.prefer_server_ciphers = Z_BVAL_P(v);
        }
        //    if (sw_zend_hash_find(vht, ZEND_STRS("ssl_session_tickets"), (void **) &v) == SUCCESS)
        //    {
        //        convert_to_boolean(v);
        //        port->ssl_config.session_tickets = Z_BVAL_P(v);
        //    }
        //    if (sw_zend_hash_find(vht, ZEND_STRS("ssl_stapling"), (void **) &v) == SUCCESS)
        //    {
        //        convert_to_boolean(v);
        //        port->ssl_config.stapling = Z_BVAL_P(v);
        //    }
        //    if (sw_zend_hash_find(vht, ZEND_STRS("ssl_stapling_verify"), (void **) &v) == SUCCESS)
        //    {
        //        convert_to_boolean(v);
        //        port->ssl_config.stapling_verify = Z_BVAL_P(v);
        //    }
        if (php_swoole_array_get_value(vht, "ssl_ciphers", v))
        {
            convert_to_string(v);
            port->ssl_config.ciphers = strdup(Z_STRVAL_P(v));
        }
        if (php_swoole_array_get_value(vht, "ssl_ecdh_curve", v))
        {
            convert_to_string(v);
            port->ssl_config.ecdh_curve = strdup(Z_STRVAL_P(v));
        }
        //    if (sw_zend_hash_find(vht, ZEND_STRS("ssl_session_cache"), (void **) &v) == SUCCESS)
        //    {
        //        convert_to_string(v);
        //        port->ssl_config.session_cache = strdup(Z_STRVAL_P(v));
        //    }
    }
#endif

    zend_update_property(swoole_server_port_class_entry_ptr, getThis(), ZEND_STRL("setting"), zset TSRMLS_CC);
}
示例#18
0
void ImportAssistant::on_assistant_prepare (GtkWidget *page)
{
  extern Settings *settings;

  // Page to confirm or change the name of the Bible.
  if (page == vbox_bible_name) {
    if (bible_name.empty()) {
      bible_name = settings->genconfig.project_get();
    }
    gtk_label_set_text (GTK_LABEL (label_project_name), bible_name.c_str());
    if (bible_name.empty()) {
      gtk_label_set_text (GTK_LABEL (label_project_name), _("No Bible selected"));
    }
    gtk_assistant_set_page_complete (GTK_ASSISTANT (assistant), vbox_bible_name, !bible_name.empty());
  }

  // Online Bible connected?
  if (page == label_online_bible_running) {
    if (my_windows_outpost->online_bible_server_connected) {
      gtk_label_set_text (GTK_LABEL (label_online_bible_running), _("Yes, connected to the Online Bible"));
    } else {
      gtk_label_set_text (GTK_LABEL (label_online_bible_running), _("No, could not connect to the Online Bible\nIs the Online Bible running?"));
    }
    gtk_assistant_set_page_complete (GTK_ASSISTANT (assistant), label_online_bible_running, my_windows_outpost->online_bible_server_connected);
  }

  // Online Bible to import. Set the available Bibles.
  if (page == vbox_online_bible_bible) {
    my_windows_outpost->OnlineBibleDirectMode = true;
    vector <ustring> bibles = combobox_get_strings (combobox_online_bible_bible);
    if (bibles.empty()) {
      ustring response = my_windows_outpost->OnlineBibleDirectCommandResponseGet ("GetVersionList");
      if (online_bible_ok_reply_validate (response)) {
        ParseLine parseline (response);
        if (!parseline.lines.empty()) {
          combobox_set_strings (combobox_online_bible_bible, parseline.lines);
          combobox_set_index (combobox_online_bible_bible, 0);
          gtk_assistant_set_page_complete (GTK_ASSISTANT (assistant), vbox_online_bible_bible, true);
        }
      }
    }
  }

  // Page for filenames to import.
  if (page == vbox_files) {
    if (files_names.empty()) {
      files_messages.push_back (_("No files selected"));
    }
    ustring label;
    label.append (_("Files count: "));
    label.append (convert_to_string ((unsigned int)files_names.size()));
    label.append ("\n");
    for (unsigned int i = 0; i < files_messages.size(); i++) {
      label.append ("\n");
      label.append (files_messages[i]);
    }
    gtk_label_set_text (GTK_LABEL (label_files), label.c_str());
    gtk_assistant_set_page_complete (GTK_ASSISTANT (assistant), vbox_files, files_messages.empty());
  }
  
  // Page for summary.
  if (page == label_summary) {
    ustring label;
    for (unsigned int i = 0; i < summary_messages.size(); i++) {
      if (i)
        label.append ("\n");
      label.append (summary_messages[i]);
    }
    if (!label.empty()) {
      gtk_label_set_text (GTK_LABEL (label_summary), label.c_str());
    }
    gtk_assistant_set_page_complete (GTK_ASSISTANT (assistant), label_summary, summary_messages.empty());
  }
}
示例#19
0
php::value database_ssdb::__call(const std::string& name, const php::parameter& param) {
    std::vector<std::string>  argv;
    // COMMAND
    std::string uname = boost::algorithm::to_lower_copy(name);
    // 找到命令
    auto f = cmd_flag.find(uname);
    if(f == cmd_flag.end()) { // 没有找到对应的方法
        zend_throw_error(nullptr, "redis command \"%s\" not found", uname.c_str());
        return php::null;
    }
    argv.push_back(uname);
    // 前缀处理
    int flag = f->second;
    if(prefix.empty() || flag & FLAG_PREFIX_NONE) { // 不处理
        for(size_t i=0;i<param.size;++i) {
            zval* v = param.get(i);
            convert_to_string(v);
            argv.push_back(std::string(Z_STRVAL_P(v), Z_STRLEN_P(v)));
        }
    }else if(flag & FLAG_PREFIX_MULTI_ALL) { // 所有参数都处理
        for(size_t i=0;i<param.size;i++) {
            zval* v = param.get(i);
            convert_to_string(v);
            std::string key = prefix;
            key.append(std::string(Z_STRVAL_P(v), Z_STRLEN_P(v)));
            argv.push_back(key);
        }
    }else if(flag & FLAG_PREFIX_MULTI_JUMP) { // 间隔处理
        for(size_t i=0;i<param.size;i++) {
            zval* v = param.get(i);
            convert_to_string(v);
            if(i%2 == 1) {
                argv.push_back(std::string(Z_STRVAL_P(v), Z_STRLEN_P(v)));
            }else{
                std::string key = prefix;
                key.append(std::string(Z_STRVAL_P(v), Z_STRLEN_P(v)));
                argv.push_back(key);
            }
        }
    }else{ // 首个参数处理
        zval* v = param.get(0);
        convert_to_string(v);
        std::string key = prefix;
        key.append(std::string(Z_STRVAL_P(v), Z_STRLEN_P(v)));
        argv.push_back(key);
        for(size_t i=1;i<param.size;++i) {
            zval* v = param.get(i);
            convert_to_string(v);
            argv.push_back(std::string(Z_STRVAL_P(v), Z_STRLEN_P(v)));
        }
    }
    const std::vector<std::string>* reply = pssdb->request(argv);
    if(reply == nullptr || reply->size() < 1) {
        zend_throw_error(nullptr, "ssdb command \"%s\" failed #1", uname.c_str());
        return php::null;
    }
    ssdb::Status status(reply);
    if(status.ok()) {
        // 返回值处理
        return database_ssdb::parse(reply, flag);
    }else if(status.not_found()) {
        return php::null;
    }else if(reply->size() > 1){
        zend_throw_error(nullptr, "ssdb command \"%s\" faild #2: %s", uname.c_str(), reply->at(1).c_str());
        return php::null;
    }else{
        zend_throw_error(nullptr, "ssdb command \"%s\" faild #3", uname.c_str());
        return php::null;
    }
}
示例#20
0
string notes_notes (void * webserver_request)
{
  Webserver_Request * request = (Webserver_Request *) webserver_request;
  Database_Notes database_notes (webserver_request);

  
  string bible = access_bible_clamp (webserver_request, request->database_config_user()->getBible());
  int book = Ipc_Focus::getBook (webserver_request);
  int chapter = Ipc_Focus::getChapter (webserver_request);
  int verse = Ipc_Focus::getVerse (webserver_request);

  
  int passage_selector = request->database_config_user()->getConsultationNotesPassageSelector();
  int edit_selector = request->database_config_user()->getConsultationNotesEditSelector();
  int non_edit_selector = request->database_config_user()->getConsultationNotesNonEditSelector();
  string status_selector = request->database_config_user()->getConsultationNotesStatusSelector();
  string bible_selector = request->database_config_user()->getConsultationNotesBibleSelector();
  string assignment_selector = request->database_config_user()->getConsultationNotesAssignmentSelector();
  bool subscription_selector = request->database_config_user()->getConsultationNotesSubscriptionSelector();
  int severity_selector = request->database_config_user()->getConsultationNotesSeveritySelector();
  int text_selector = request->database_config_user()->getConsultationNotesTextSelector();
  string search_text = request->database_config_user()->getConsultationNotesSearchText();
  int passage_inclusion_selector = request->database_config_user()->getConsultationNotesPassageInclusionSelector();
  int text_inclusion_selector = request->database_config_user()->getConsultationNotesTextInclusionSelector();

  
  // The Bibles the current user has access to.
  vector <string> bibles = access_bible_bibles (webserver_request, request->session_logic()->currentUser ());
  
  
  // The admin disables notes selection on Bibles,
  // so the admin sees all notes, including notes referring to non-existing Bibles.
  if (request->session_logic ()->currentLevel () == Filter_Roles::admin ()) bibles.clear ();
  
  
  vector <int> identifiers = database_notes.selectNotes (bibles, book, chapter, verse, passage_selector, edit_selector, non_edit_selector, status_selector, bible_selector, assignment_selector, subscription_selector, severity_selector, text_selector, search_text, -1);
  
  
  // In case there aren't too many notes, there's enough time to sort them in passage order.
  if (identifiers.size () <= 200) {
    vector <int> passage_sort_keys;
    for (auto & identifier : identifiers) {
      int passage_sort_key = 0;
      vector <float> numeric_passages;
      vector <Passage> passages = database_notes.getPassages (identifier);
      for (auto & passage : passages) {
        numeric_passages.push_back (filter_passage_to_integer (passage));
      }
      if (!numeric_passages.empty ()) {
        float average = accumulate (numeric_passages.begin (), numeric_passages.end (), 0) / numeric_passages.size ();
        passage_sort_key = round (average);
      }
      passage_sort_keys.push_back (passage_sort_key);
    }
    quick_sort (passage_sort_keys, identifiers, 0, identifiers.size ());
  }

  
  string notesblock;
  for (auto & identifier : identifiers) {

    string summary = database_notes.getSummary (identifier);
    vector <Passage> passages = database_notes.getPassages (identifier);
    string verses = filter_passage_display_inline (passages);
    // A simple way to make it easier to see the individual notes in the list,
    // when the summaries of some notes are long, is to display the passage first.
    summary.insert (0, verses + " | ");

    string verse_text;
    if (passage_inclusion_selector) {
      vector <Passage> passages = database_notes.getPassages (identifier);
      for (auto & passage : passages) {
        string usfm = request->database_bibles()->getChapter (bible, passage.book, passage.chapter);
        string text = usfm_get_verse_text (usfm, convert_to_int (passage.verse));
        if (!verse_text.empty ()) verse_text.append ("<br>");
        verse_text.append (text);
      }
    }
    
    string content;
    if (text_inclusion_selector) {
      content = database_notes.getContents (identifier);
    }
    
    notesblock.append ("<a name=\"note" + convert_to_string (identifier) + "\"></a>\n");
    notesblock.append ("<p><a href=\"note?id=" + convert_to_string (identifier) + "\">" + summary + "</a></p>\n");
    if (!verse_text.empty ()) notesblock.append ("<p>" + verse_text + "</p>\n");
    if (!content.empty ()) notesblock.append ("<p>" + content + "</p>\n");
  }

  
  if (identifiers.empty ()) {
    return translate("This selection does not display any notes.");
  }
  return notesblock;
}
示例#21
0
static zend_always_inline int process_nested_data(UNSERIALIZE_PARAMETER, HashTable *ht, zend_long elements, int objprops)
{
	while (elements-- > 0) {
		zval key, *data, d, *old_data;
		zend_ulong idx;

		ZVAL_UNDEF(&key);

		if (!php_var_unserialize_ex(&key, p, max, NULL, classes)) {
			zval_dtor(&key);
			return 0;
		}

		data = NULL;
		ZVAL_UNDEF(&d);

		if (!objprops) {
			if (Z_TYPE(key) == IS_LONG) {
				idx = Z_LVAL(key);
numeric_key:
				if (UNEXPECTED((old_data = zend_hash_index_find(ht, idx)) != NULL)) {
					//??? update hash
					var_push_dtor(var_hash, old_data);
					data = zend_hash_index_update(ht, idx, &d);
				} else {
					data = zend_hash_index_add_new(ht, idx, &d);
				}
			} else if (Z_TYPE(key) == IS_STRING) {
				if (UNEXPECTED(ZEND_HANDLE_NUMERIC(Z_STR(key), idx))) {
					goto numeric_key;
				}
				if (UNEXPECTED((old_data = zend_hash_find(ht, Z_STR(key))) != NULL)) {
					//??? update hash
					var_push_dtor(var_hash, old_data);
					data = zend_hash_update(ht, Z_STR(key), &d);
				} else {
					data = zend_hash_add_new(ht, Z_STR(key), &d);
				}
			} else {
				zval_dtor(&key);
				return 0;
			}
		} else {
			if (EXPECTED(Z_TYPE(key) == IS_STRING)) {
string_key:
				if ((old_data = zend_hash_find(ht, Z_STR(key))) != NULL) {
					if (Z_TYPE_P(old_data) == IS_INDIRECT) {
						old_data = Z_INDIRECT_P(old_data);
					}
					var_push_dtor(var_hash, old_data);
					data = zend_hash_update_ind(ht, Z_STR(key), &d);
				} else {
					data = zend_hash_add_new(ht, Z_STR(key), &d);
				}
			} else if (Z_TYPE(key) == IS_LONG) {
				/* object properties should include no integers */
				convert_to_string(&key);
				goto string_key;
			} else {
				zval_dtor(&key);
				return 0;
			}
		}

		zval_dtor(&key);

		if (!php_var_unserialize_ex(data, p, max, var_hash, classes)) {
			return 0;
		}

		if (elements && *(*p-1) != ';' && *(*p-1) != '}') {
			(*p)--;
			return 0;
		}
	}

	return 1;
}
示例#22
0
文件: usfm.cpp 项目: alerque/bibledit
// This function compares the $newtext with the $oldtext.
// It returns an empty string if the difference is below the limit set for the Bible.
// It returns a message specifying the difference if it exceeds that limit.
string usfm_save_is_safe (void * webserver_request, string oldtext, string newtext, bool chapter)
{
  // Two texts are equal: safe.
  if (newtext == oldtext) return "";

  Webserver_Request * request = (Webserver_Request *) webserver_request;

  // Allowed percentage difference.
  int allowed_percentage = request->database_config_user ()->getEditingAllowedDifferenceVerse ();
  if (chapter) allowed_percentage = request->database_config_user ()->getEditingAllowedDifferenceChapter ();

  // The length of the new text should not differ more than a set percentage from the old text.
  float existingLength = oldtext.length();
  float newLength = newtext.length ();
  int percentage = 100 * (newLength - existingLength) / existingLength;
  percentage = abs (percentage);
  if (percentage > 100) percentage = 100;
  if (percentage > allowed_percentage) {
    Database_Logs::log ("The text was not saved for safety reasons. The length differs " + convert_to_string (percentage) + "% from the existing text. Make smaller changes and save more often. Or relax the restriction in the Bible's editing settings.");
    Database_Logs::log (newtext);
    return translate ("Text length differs too much");
  }
  
  // The new text should be at least a set percentage similar to the old text.
  percentage = filter_diff_similarity (oldtext, newtext);
  if (percentage < (100 - allowed_percentage)) {
    Database_Logs::log ("The text was not saved for safety reasons. The new text is " + convert_to_string (percentage) + "% similar to the existing text. Make smaller changes and save more often. Or relax the restriction in the Bible's editing settings.");
    Database_Logs::log (newtext);
    return translate ("Text content differs too much");
  }
  
  // Safety checks have passed.
  return "";
}
示例#23
0
string search_search2 (void * webserver_request)
{
    Webserver_Request * request = (Webserver_Request *) webserver_request;


    Database_Volatile database_volatile = Database_Volatile ();


    string siteUrl = config_logic_site_url ();


    string bible = request->database_config_user()->getBible ();
    if (request->query.count ("bible")) bible = request->query ["bible"];


    bool hit_is_set = request->query.count ("h");
    bool query_is_set = request->query.count ("q");
    int identifier = convert_to_int (request->query ["i"]);
    string query = request->query ["q"];
    string hit = request->query ["h"];


    // Get one search hit.
    if (hit_is_set) {


        // Retrieve the search parameters from the volatile database.
        string query = database_volatile.getValue (identifier, "query");
        //bool casesensitive = convert_to_bool (database_volatile.getValue (identifier, "casesensitive"));
        bool plaintext = convert_to_bool (database_volatile.getValue (identifier, "plaintext"));


        // Get the Bible and passage for this identifier.
        Passage details = Passage::from_text (hit);
        string bible = details.bible;
        int book = details.book;
        int chapter = details.chapter;
        string verse = details.verse;


        // Get the plain text or USFM.
        string text;
        if (plaintext) {
            text = search_logic_get_bible_verse_text (bible, book, chapter, convert_to_int (verse));
        } else {
            text = search_logic_get_bible_verse_usfm (bible, book, chapter, convert_to_int (verse));
        }


        // Format it.
        string link = filter_passage_link_for_opening_editor_at (book, chapter, verse);
        text =  filter_string_markup_words ({query}, text);
        string output = "<div>" + link + " " + text + "</div>";


        // Output to browser.
        return output;
    }


    // Perform the initial search.
    if (query_is_set) {


        // Get extra search parameters and store them all in the volatile database.
        bool casesensitive = (request->query ["c"] == "true");
        bool plaintext = (request->query ["p"] == "true");
        bool currentbook = (request->query ["b"] == "true");
        string sharing = request->query ["s"];
        database_volatile.setValue (identifier, "query", query);
        database_volatile.setValue (identifier, "casesensitive", convert_to_string (casesensitive));
        database_volatile.setValue (identifier, "plaintext", convert_to_string (plaintext));


        // Deal with case sensitivity.
        // Deal with whether to search the plain text, or the raw USFM.
        // Fetch the initial set of hits.
        vector <Passage> passages;
        if (plaintext) {
            if (casesensitive) {
                passages = search_logic_search_bible_text_case_sensitive (bible, query);
            } else {
                passages = search_logic_search_bible_text (bible, query);
            }
        } else {
            if (casesensitive) {
                passages = search_logic_search_bible_usfm_case_sensitive (bible, query);
            } else {
                passages = search_logic_search_bible_usfm (bible, query);
            }
        }


        // Deal with possible searching in the current book only.
        if (currentbook) {
            int book = Ipc_Focus::getBook (request);
            vector <Passage> bookpassages;
            for (auto & passage : passages) {
                if (book == passage.book) {
                    bookpassages.push_back (passage);
                }
            }
            passages = bookpassages;
        }


        // Deal with how to share the results.
        vector <string> hits;
        for (auto & passage : passages) {
            hits.push_back (passage.to_text ());
        }
        if (sharing != "load") {
            vector <string> loaded_hits = filter_string_explode (database_volatile.getValue (identifier, "hits"), '\n');
            if (sharing == "add") {
                hits.insert (hits.end(), loaded_hits.begin(), loaded_hits.end());
            }
            if (sharing == "remove") {
                hits = filter_string_array_diff (loaded_hits, hits);
            }
            if (sharing == "intersect") {
                hits = array_intersect (loaded_hits, hits);
            }
            hits = array_unique (hits);
        }


        // Generate one string from the hits.
        string output = filter_string_implode (hits, "\n");


        // Store search hits in the volatile database.
        database_volatile.setValue (identifier, "hits", output);


        // Output results.
        return output;
    }


    // Build the advanced search page.
    string page;
    Assets_Header header = Assets_Header (translate("Search"), request);
    header.setNavigator ();
    header.addBreadCrumb (menu_logic_search_menu (), menu_logic_search_text ());
    page = header.run ();
    Assets_View view;
    view.set_variable ("bible", bible);
    string script = "var searchBible = \"" + bible + "\";";
    view.set_variable ("script", script);
    page += view.render ("search", "search2");
    page += Assets_Page::footer ();
    return page;
}
示例#24
0
文件: usfm.cpp 项目: alerque/bibledit
// Function to safely store a verse.
// It saves the verse if the new USFM does not differ too much from the existing USFM.
// On success it returns an empty message.
// On failure it returns a message that specifies the reason why it could not be saved.
// This function proves useful in cases that the text in the Bible editor gets corrupted
// due to human error.
// It also is useful in cases where the session is deleted from the server,
// where the text in the editors would get corrupted.
// It also is useful in view of an unstable connection between browser and server, to prevent data corruption.
// It handles combined verses.
string usfm_safely_store_verse (void * webserver_request, string bible, int book, int chapter, int verse, string usfm)
{
  Webserver_Request * request = (Webserver_Request *) webserver_request;
  
  usfm = filter_string_trim (usfm);

  // Check that the USFM to be saved is for the correct verse.
  vector <int> save_verses = usfm_get_verse_numbers (usfm);
  if ((verse != 0) && !save_verses.empty ()) {
    save_verses.erase (save_verses.begin());
  }
  if (save_verses.empty ()) {
    Database_Logs::log ("The USFM contains no verse information: " + usfm);
    return translate ("Missing verse number");
  }
  if (!in_array (verse, save_verses)) {
    vector <string> vss;
    for (auto vs : save_verses) vss.push_back (convert_to_string (vs));
    Database_Logs::log ("The USFM contains verse(s) " + filter_string_implode (vss, " ") + " while it wants to save to verse " + convert_to_string (verse) + ": " + usfm);
    return translate ("Verse mismatch");
  }

  // Get the existing chapter USFM.
  string chapter_usfm = request->database_bibles()->getChapter (bible, book, chapter);
  
  // Get the existing USFM fragment for the verse to save.
  string existing_verse_usfm = usfm_get_verse_text (chapter_usfm, verse);
  existing_verse_usfm = filter_string_trim (existing_verse_usfm);
  
  // Check that there is a match between the existing verse numbers and the verse numbers to save.
  vector <int> existing_verses = usfm_get_verse_numbers (existing_verse_usfm);
  save_verses = usfm_get_verse_numbers (usfm);
  bool verses_match = true;
  if (save_verses.size () == existing_verses.size ()) {
    for (unsigned int i = 0; i < save_verses.size (); i++) {
      if (save_verses [i] != existing_verses [i]) verses_match = false;
    }
  } else {
    verses_match = false;
  }
  if (!verses_match) {
    vector <string> existing, save;
    for (auto vs : existing_verses) existing.push_back (convert_to_string (vs));
    for (auto vs : save_verses) save.push_back (convert_to_string (vs));
    Database_Logs::log ("The USFM contains verse(s) " + filter_string_implode (save, " ") + " which would overwrite a fragment that contains verse(s) " + filter_string_implode (existing, " ") + ": " + usfm);
    return translate ("Cannot overwrite another verse");
  }

  // Bail out if the new USFM is the same as the existing.
  if (usfm == existing_verse_usfm) {
    return "";
  }

  // Check maximum difference between new and existing USFM.
  string message = usfm_save_is_safe (webserver_request, existing_verse_usfm, usfm, false);
  if (!message.empty ()) return message;
  
  // Store the new verse USFM in the existing chapter USFM.
  size_t pos = chapter_usfm.find (existing_verse_usfm);
  size_t length = existing_verse_usfm.length ();
  chapter_usfm.erase (pos, length);
  chapter_usfm.insert (pos, usfm);
  
  // Safety checks have passed: Save chapter.
  Bible_Logic::storeChapter (bible, book, chapter, chapter_usfm);

  // Done: OK.
  return "";
}
示例#25
0
vector <ustring> mechon_mamre_extract_contents (const ustring& file, unsigned int chapter)
{
  // Usfm data.
  vector <ustring> lines;
  
  // Convert chapter number to USFM code.
  lines.push_back("\\c " + convert_to_string(chapter));
  lines.push_back("\\p");
  
  // Read the text of the .htm file, and select only the .htm lines that 
  // contain the actual text.
  vector < ustring > htmlines;
  {
    ReadText rt (file, true, false);
    // Find lower boundary: the relevant parts start with a verse number.
    unsigned int lower_boundary = 0;
    for (unsigned int i = 0; i < rt.lines.size(); i++) {
      if (rt.lines[i].find("A NAME=") != string::npos) {
        lower_boundary = i;
        break;
      }
    }
    // Find higher boundary: the relevant part ends with a verse number 
    // that is one past the last verse.
    unsigned int upper_boundary = 0;
    for (unsigned int i = rt.lines.size() - 1; i > 0; i--) {
      if (rt.lines[i].find("A NAME=") != string::npos) {
        upper_boundary = i;
        upper_boundary++;
        break;
      }
    }
    // Store the relevant html lines that contain the verses.
    for (unsigned int i = lower_boundary; i <= upper_boundary; i++) {
      htmlines.push_back(rt.lines[i]);
    }
  }

  // Go through the relevant text and extract the verses.
  ustring verse;
  for (unsigned int ln = 0; ln < htmlines.size(); ln++) {
    ustring s = number_in_string(htmlines[ln]);
    if (!s.empty()) {
      verse = "\\v " + s;
    } else {
      // A text line could be looking so (Psalms 1:1):
      // <P><B>א</B> אַ֥שְֽׁרֵי הָאִ֗ישׁ    אֲשֶׁ֤ר ׀ לֹ֥א הָלַךְ֮ בַּֽעֲצַ֪ת רְשָׁ֫עִ֥ים<BR>וּבְדֶ֣רֶךְ חַ֭טָּאִים לֹ֥א עָמָ֑ד    וּבְמוֹשַׁ֥ב לֵ֝צִ֗ים לֹ֣א יָשָֽׁב׃<BR>
      ustring line = htmlines[ln];
      // Convert <BR>, </P>, etc.
      replace_text(line, "<BR>", "\n\\nb\n");
      replace_text(line, "</P>", "\n\\p\n");
      replace_text(line, "<BIG>", "");
      replace_text(line, "</BIG>", "");
      replace_text(line, "{פ}", "");
      replace_text(line, "{ס}", "");
      size_t position = line.find_last_of(">");
      line.erase(0, ++position);
      line = trim(line);
      lines.push_back(verse + " " + line);
    }
  }
  
  // Return the data.
  return lines;  
}
示例#26
0
static PyObject *Py_convert_to_string(PyObject *self, PyObject *args, PyObject *kwds)
{
    py::PathIterator path;
    agg::trans_affine trans;
    agg::rect_d cliprect;
    PyObject *simplifyobj;
    bool simplify = false;
    SketchParams sketch;
    int precision;
    PyObject *codesobj;
    char *codes[5];
    int postfix;
    char *buffer = NULL;
    size_t buffersize;
    PyObject *result;
    int status;

    if (!PyArg_ParseTuple(args,
                          "O&O&O&OO&iOi:convert_to_string",
                          &convert_path,
                          &path,
                          &convert_trans_affine,
                          &trans,
                          &convert_rect,
                          &cliprect,
                          &simplifyobj,
                          &convert_sketch_params,
                          &sketch,
                          &precision,
                          &codesobj,
                          &postfix)) {
        return NULL;
    }

    if (simplifyobj == Py_None) {
        simplify = path.should_simplify();
    } else if (PyObject_IsTrue(simplifyobj)) {
        simplify = true;
    }

    if (!PySequence_Check(codesobj)) {
        return NULL;
    }
    if (PySequence_Size(codesobj) != 5) {
        PyErr_SetString(
            PyExc_ValueError,
            "codes must be a 5-length sequence of byte strings");
        return NULL;
    }
    for (int i = 0; i < 5; ++i) {
        PyObject *item = PySequence_GetItem(codesobj, i);
        if (item == NULL) {
            return NULL;
        }
        codes[i] = PyBytes_AsString(item);
        if (codes[i] == NULL) {
            return NULL;
        }
    }

    CALL_CPP("convert_to_string",
             (status = convert_to_string(
                 path, trans, cliprect, simplify, sketch,
                 precision, codes, (bool)postfix, &buffer,
                 &buffersize)));

    if (status) {
        free(buffer);
        if (status == 1) {
            PyErr_SetString(PyExc_MemoryError, "Memory error");
        } else if (status == 2) {
            PyErr_SetString(PyExc_ValueError, "Malformed path codes");
        }
        return NULL;
    }

    if (buffersize == 0) {
        result = PyBytes_FromString("");
    } else {
        result = PyBytes_FromStringAndSize(buffer, buffersize);
    }

    free(buffer);

    return result;
}
示例#27
0
/****************
 * Print SEXP to buffer using the MODE.  Returns the length of the
 * SEXP in buffer or 0 if the buffer is too short (We have at least an
 * empty list consisting of 2 bytes).  If a buffer of NULL is provided,
 * the required length is returned.
 */
size_t
gcry_sexp_sprint (const gcry_sexp_t list, int mode,
                  void *buffer, size_t maxlength )
{
  static unsigned char empty[3] = { ST_OPEN, ST_CLOSE, ST_STOP };
  const unsigned char *s;
  char *d;
  DATALEN n;
  char numbuf[20];
  size_t len = 0;
  int i, indent = 0;

  s = list? list->d : empty;
  d = buffer;
  while ( *s != ST_STOP )
    {
      switch ( *s )
        {
        case ST_OPEN:
          s++;
          if ( mode != GCRYSEXP_FMT_CANON )
            {
              if (indent)
                len++;
              len += indent;
            }
          len++;
          if ( buffer )
            {
              if ( len >= maxlength )
                return 0;
              if ( mode != GCRYSEXP_FMT_CANON )
                {
                  if (indent)
                    *d++ = '\n';
                  for (i=0; i < indent; i++)
                    *d++ = ' ';
                }
              *d++ = '(';
	    }
          indent++;
          break;
        case ST_CLOSE:
          s++;
          len++;
          if ( buffer )
            {
              if ( len >= maxlength )
                return 0;
              *d++ = ')';
	    }
          indent--;
          if (*s != ST_OPEN && *s != ST_STOP && mode != GCRYSEXP_FMT_CANON)
            {
              len++;
              len += indent;
              if (buffer)
                {
                  if (len >= maxlength)
                    return 0;
                  *d++ = '\n';
                  for (i=0; i < indent; i++)
                    *d++ = ' ';
                }
            }
          break;
        case ST_DATA:
          s++;
          memcpy ( &n, s, sizeof n ); s += sizeof n;
          if (mode == GCRYSEXP_FMT_ADVANCED)
            {
              int type;
              size_t nn;

              switch ( (type=suitable_encoding (s, n)))
                {
                case 1: nn = convert_to_string (s, n, NULL); break;
                case 2: nn = convert_to_token (s, n, NULL); break;
                default: nn = convert_to_hex (s, n, NULL); break;
                }
              len += nn;
              if (buffer)
                {
                  if (len >= maxlength)
                    return 0;
                  switch (type)
                    {
                    case 1: convert_to_string (s, n, d); break;
                    case 2: convert_to_token (s, n, d); break;
                    default: convert_to_hex (s, n, d); break;
                    }
                  d += nn;
                }
              if (s[n] != ST_CLOSE)
                {
                  len++;
                  if (buffer)
                    {
                      if (len >= maxlength)
                        return 0;
                      *d++ = ' ';
                    }
                }
            }
          else
            {
              sprintf (numbuf, "%u:", (unsigned int)n );
              len += strlen (numbuf) + n;
              if ( buffer )
                {
                  if ( len >= maxlength )
		    return 0;
                  d = stpcpy ( d, numbuf );
                  memcpy ( d, s, n ); d += n;
                }
            }
          s += n;
          break;
        default:
          BUG ();
	}
    }
  if ( mode != GCRYSEXP_FMT_CANON )
    {
      len++;
      if (buffer)
        {
          if ( len >= maxlength )
            return 0;
          *d++ = '\n';
        }
    }
  if (buffer)
    {
      if ( len >= maxlength )
        return 0;
      *d++ = 0; /* for convenience we make a C string */
    }
  else
    len++; /* we need one byte more for this */

  return len;
}
示例#28
0
// Generates a URL for connecting to Bibledit Cloud.
// $address is the website.
// $port is the port number.
// $path is the path after the website.
string client_logic_url (string address, int port, string path)
{
  return address + ":" + convert_to_string (port) + "/" + path;
}
示例#29
0
static inline int process_nested_data(UNSERIALIZE_PARAMETER, HashTable *ht, long elements, int objprops)
{
	while (elements-- > 0) {
		zval *key, *data, **old_data;

		ALLOC_INIT_ZVAL(key);

		if (!php_var_unserialize(&key, p, max, NULL TSRMLS_CC)) {
			zval_dtor(key);
			FREE_ZVAL(key);
			return 0;
		}

		if (Z_TYPE_P(key) != IS_LONG && Z_TYPE_P(key) != IS_STRING) {
			zval_dtor(key);
			FREE_ZVAL(key);
			return 0;
		}

		ALLOC_INIT_ZVAL(data);

		if (!php_var_unserialize(&data, p, max, var_hash TSRMLS_CC)) {
			zval_dtor(key);
			FREE_ZVAL(key);
			zval_dtor(data);
			FREE_ZVAL(data);
			return 0;
		}

		if (!objprops) {
			switch (Z_TYPE_P(key)) {
			case IS_LONG:
				if (zend_hash_index_find(ht, Z_LVAL_P(key), (void **)&old_data)==SUCCESS) {
					var_push_dtor(var_hash, old_data);
				}
				zend_hash_index_update(ht, Z_LVAL_P(key), &data, sizeof(data), NULL);
				break;
			case IS_STRING:
				if (zend_symtable_find(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, (void **)&old_data)==SUCCESS) {
					var_push_dtor(var_hash, old_data);
				}
				zend_symtable_update(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, &data, sizeof(data), NULL);
				break;
			}
		} else {
			/* object properties should include no integers */
			convert_to_string(key);
			zend_hash_update(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, &data,
					sizeof data, NULL);
		}
		
		zval_dtor(key);
		FREE_ZVAL(key);

		if (elements && *(*p-1) != ';' && *(*p-1) != '}') {
			(*p)--;
			return 0;
		}
	}

	return 1;
}
示例#30
0
string search_logic_chapter_file (string bible, int book, int chapter)
{
  return search_logic_book_fragment (bible, book) + convert_to_string (chapter);
}