void Database_Logs::log (string description, int level) { // No new lines. description = filter_string_str_replace ("\n", " ", description); // Discard empty line. if (filter_string_trim (description).empty()) return; // Truncate long entry. int length = description.length (); if (length > 1000) { description.erase (1000); description.append ("... This entry was too large and has been truncated: " + convert_to_string (length) + " bytes"); } // Save this logbook entry to a filename with seconds and microseconds. string seconds = convert_to_string (filter_date_seconds_since_epoch ()); string time = seconds + filter_string_fill (convert_to_string (filter_date_numerical_microseconds ()), 8, '0'); string file = filter_url_create_path (folder (), time); // The microseconds granularity depends on the platform. // On Windows it is lower than on Linux. // There may be the rare case of more than one entry per file. // Append the data so it won't overwrite an earlier entry. if (file_exists (file)) { description.insert (0, " | "); } else { description.insert (0, convert_to_string (level) + " " + seconds + " "); } filter_url_file_put_contents_append (file, description); // Delay to cover for lower usec granularity on Windows. if (config_logic_windows ()) { this_thread::sleep_for (chrono::milliseconds (1)); } }
void Navigation_Passage::recordHistory (void * webserver_request, int book, int chapter, int verse) { Webserver_Request * request = (Webserver_Request *) webserver_request; string user = request->session_logic()->currentUser (); Database_Navigation database_navigation; database_navigation.record (filter_date_seconds_since_epoch (), user, book, chapter, verse); }
void client_index_enable_client (void * webserver_request, string username, string password, int level) { Webserver_Request * request = (Webserver_Request *) webserver_request; // Enable client mode upon a successful connection. client_logic_enable_client (true); // Remove all users from the database, and add the current one. client_index_remove_all_users (request); request->database_users ()->add_user (username, password, level, ""); // Update the username and the level in the current session. request->session_logic ()->setUsername (username); request->session_logic ()->currentLevel (true); // Clear all pending note actions and Bible actions and settings updates. Database_NoteActions database_noteactions; Database_BibleActions database_bibleactions; database_noteactions.clear (); database_noteactions.create (); database_bibleactions.clear (); database_bibleactions.create (); request->session_logic ()->setUsername (username); request->database_config_user()->setUpdatedSettings ({}); Database_Config_General::setUnsentBibleDataTime (0); Database_Config_General::setUnreceivedBibleDataTime (filter_date_seconds_since_epoch ()); // Set it to repeat sync every so often. if (Database_Config_General::getRepeatSendReceive () == 0) { Database_Config_General::setRepeatSendReceive (2); } // Schedule a sync operation straight-away. sendreceive_queue_sync (-1); }
// If $minute is negative, it syncs. // If $minute >=0, it determines from the settings whether to sync. void sendreceive_queue_sync (int minute) { // Deal with a numerical minute to find out whether it's time to automatically sync. if (minute >= 0) { int repeat = Database_Config_General::getRepeatSendReceive (); // Sync every hour. if (repeat == 1) { minute = minute % 60; if (minute == 0) minute = -1; } // Sync every five minutes. if (repeat == 2) { minute = minute % 5; if (minute == 0) minute = -1; } } // Send and receive: It is time now, or it is manual. // Only queue a sync task if it is not running at the moment. if (minute < 0) { // Send / receive only works in Client mode. if (client_logic_client_enabled ()) { if (tasks_logic_queued (SYNCBIBLES)) { Database_Logs::log ("Still synchronizing Bibles"); } else { tasks_logic_queue (SYNCBIBLES); } if (tasks_logic_queued (SYNCNOTES)) { Database_Logs::log ("Still synchronizing Notes"); } else { tasks_logic_queue (SYNCNOTES); } if (tasks_logic_queued (SYNCSETTINGS)) { Database_Logs::log ("Still synchronizing Settings"); } else { tasks_logic_queue (SYNCSETTINGS); } if (tasks_logic_queued (SYNCCHANGES)) { Database_Logs::log ("Still synchronizing Changes"); } else { tasks_logic_queue (SYNCCHANGES); } if (tasks_logic_queued (SYNCFILES)) { Database_Logs::log ("Still synchronizing Files"); } else { tasks_logic_queue (SYNCFILES); } // Sync resources always, because it checks on its own whether to do something. tasks_logic_queue (SYNCRESOURCES); } // Store the most recent time that the sync action ran. Database_Config_General::setLastSendReceive (filter_date_seconds_since_epoch ()); } }
void Database_Confirm::trim () { // Leave entries for no more than 30 days. unsigned int time = filter_date_seconds_since_epoch () - 2592000; SqliteDatabase sql (filename ()); sql.add ("DELETE FROM confirm WHERE timestamp <"); sql.add (time); sql.add (";"); sql.execute (); }
// Returns the name of a temporary file. string filter_url_tempfile (const char * directory) { string filename = convert_to_string (filter_date_seconds_since_epoch ()) + convert_to_string (filter_date_numerical_microseconds ()); if (directory) { filename = filter_url_create_path (directory, filename); } else { filename = filter_url_create_root_path ("tmp", filename); } return filename; }
// handleEmailComment - handles an email received from from with subject subject and body body. // Returns true if the mail was processed, else false. // The email is considered to have been processed if it comments on an existing Consultation Note. bool Notes_Logic::handleEmailComment (string from, string subject, string body) { // Check whether the Consultation Notes Identifier in the subject exists in the notes database. // The CNID looks like: (CNID123456789) size_t pos = subject.find ("(CNID"); if (pos == string::npos) return false; subject = subject.substr (pos + 5); pos = subject.find (")"); if (pos == string::npos) return false; subject = subject.substr (0, pos); // Webserver request. Webserver_Request * request = (Webserver_Request *) webserver_request; // At this stage, the subject contains an identifier. // Check that the identifier is an existing Consultation Note. int identifier = convert_to_int (subject); Database_Notes database_notes (webserver_request); if (!database_notes.identifierExists (identifier)) return false; // Check that the from address of the email belongs to an existing user. // Or else use the obfuscated email address as the user name. string username; from = filter_string_extract_email (from); if (request->database_users()->emailExists (from)) { username = request->database_users()->getEmailToUser (from); } else { username = from; username = filter_string_str_replace ("@", " ", username); username = filter_string_str_replace (".", " ", username); } // Clean the email's body. string year = convert_to_string (filter_date_numerical_year (filter_date_seconds_since_epoch ())); string sender = Database_Config_General::getSiteMailName(); body = filter_string_extract_body (body, year, sender); // Remove any new lines from the body. This cleans up the email considerably, // because some emails that get posted would otherwise look untidy, // when the many new lines take up a lot of space. body = filter_string_str_replace ("\n", " ", body); // Make comment on the consultation note. string sessionuser = request->session_logic ()->currentUser (); request->session_logic ()->setUsername (username); addComment (identifier, body); request->session_logic ()->setUsername (sessionuser); // Mail confirmation to the username. if (request->database_config_user()->getUserNotifyMeOfMyPosts (username)) { Database_Mail database_mail = Database_Mail (webserver_request); string subject = translate("Your comment was posted"); subject.append (" [CNID"); subject.append (convert_to_string (identifier)); subject.append ("]"); database_mail.send (username, subject, body); } // Log operation. Database_Logs::log ("Comment posted: " + body); // Job done. return true; }
void tmp_tmp () { Database_Logs::log ("Removing expired temporal files", Filter_Roles::admin ()); int expired = filter_date_seconds_since_epoch () - (3600 * 24 * 3); string directory = filter_url_create_root_path ("tmp"); vector <string> names = filter_url_scandir (directory); for (auto & name : names) { if (name.find ("tmp.") == 0) continue; string filename = filter_url_create_path (directory, name); int mtime = filter_url_filemtime (filename); if (mtime < expired) { filter_url_rmdir (filename); filter_url_unlink (filename); } } }
// stores a confirmation cycle void Database_Confirm::store (unsigned int id, string query, string to, string subject, string body) { SqliteDatabase sql (filename ()); sql.add ("INSERT INTO confirm VALUES ("); sql.add (id); sql.add (","); sql.add (query); sql.add (","); sql.add (filter_date_seconds_since_epoch ()); sql.add (","); sql.add (to); sql.add (","); sql.add (subject); sql.add (","); sql.add (body); sql.add (");"); sql.execute (); }
// Queue task $command to run later, with $parameters for that task. void tasks_logic_queue (string command, vector <string> parameters) { // The file on disk will contain the command on the first line, // and any parameters on the following lines, one parameters per line. vector <string> lines; lines.push_back (command); lines.insert (lines.end(), parameters.begin(), parameters.end()); // The filename to write to contains seconds and microseconds. string seconds = convert_to_string (filter_date_seconds_since_epoch ()); string time = seconds + filter_string_fill (convert_to_string (filter_date_numerical_microseconds ()), 8, '0'); string file = filter_url_create_path (tasks_logic_folder (), time); // On Windows the microtime is not fine enough. // This leads to one task overwriting a previous one in case it is queued immediately after. // Deal with that problem here: Ensure the filename is unique. file = filter_url_unique_path (file); // Save it. command = filter_string_implode (lines, "\n"); filter_url_file_put_contents (file, command); }
// Function that looks if, at app startup, it needs to queue sync operations in the client. void sendreceive_queue_startup () { // Next second when it is supposed to sync. int next_second = Database_Config_General::getLastSendReceive (); // Check how often to repeat the sync action. int repeat = Database_Config_General::getRepeatSendReceive (); if (repeat == 1) { // Repeat every hour. next_second += 3600; } else if (repeat == 2) { // Repeat every five minutes. next_second += 300; } else { // No repetition. return; } // When the current time is past the next time it is supposed to sync, start the sync. if (filter_date_seconds_since_epoch () >= next_second) { sendreceive_queue_sync (-1); } }
// This handles email to users. // identifier: the note that is being handled. // label: prefix to the subject line of the email. // users: array of users to be mailed. // postpone: whether to postpone sending the email till the evening. void Notes_Logic::emailUsers (int identifier, const string& label, const vector <string> & users, bool postpone) { // Databases. Database_Notes database_notes (webserver_request); Database_Mail database_mail = Database_Mail(webserver_request); // Send mail to all users. string summary = database_notes.getSummary (identifier); string passages = filter_passage_display_inline (database_notes.getPassages (identifier)); string contents = database_notes.getContents (identifier); // Include links to the Cloud: One to the note, and one to the active desktop. contents.append ("<br>\n"); contents.append ("<p>"); contents.append ("<a href=\""); string notelink = Database_Config_General::getSiteURL () + notes_note_url () + "?id=" + convert_to_string (identifier); contents.append (notelink); contents.append ("\">"); contents.append (translate ("View or respond online")); contents.append ("</a>"); contents.append (" " + translate ("or") + " "); contents.append ("<a href=\""); string desktoplink = Database_Config_General::getSiteURL () + workbench_index_url () + "?note=" + convert_to_string (identifier); contents.append (desktoplink); contents.append ("\">"); contents.append (translate ("open the desktop online")); contents.append ("</a>"); contents.append ("</p>\n"); string mailto = "mailto:" + Database_Config_General::getSiteMailAddress () + "?subject=(CNID" + convert_to_string (identifier) + ")"; contents.append ("<p><a href=\""); contents.append (mailto); contents.append ("\">Respond by email</a></p>\n"); // Deal with possible postponing email till 9 PM. int timestamp = filter_date_seconds_since_epoch (); if (postpone) { int localseconds = filter_date_local_seconds (timestamp); float localhour = filter_date_numerical_hour (localseconds) + (float) filter_date_numerical_minute (localseconds) / 60; if (localhour < 21) { float difference = 21 - localhour; timestamp += (3600 * difference) - 10; } } // Send (but not in client mode). for (auto & user : users) { if (!client_logic_client_enabled ()) { string subject = label; subject.append (" | "); subject.append (passages); subject.append (" | "); subject.append (summary); subject.append (" | (CNID"); subject.append (convert_to_string (identifier)); subject.append (")"); database_mail.send (user, subject, contents, timestamp); } } }
void timer_index () { bool client = client_logic_client_enabled (); int previous_second = -1; int previous_minute = -1; int previous_fraction = -1; while (config_globals_running) { try { // Wait shortly. this_thread::sleep_for (chrono::milliseconds (100)); // Wait tilll the data structures have been initialized. if (!config_globals_data_initialized) continue; // The current time, localized. int seconds_since_epoch = filter_date_seconds_since_epoch (); int local_seconds = filter_date_local_seconds (seconds_since_epoch); int second = filter_date_numerical_second (local_seconds); int minute = filter_date_numerical_minute (local_seconds); int hour = filter_date_numerical_hour (local_seconds); int weekday = filter_date_numerical_week_day (local_seconds); // Run once per second. if (second == previous_second) continue; previous_second = second; // Every second: Deal with queued and/or active tasks. tasks_run_check (); // Run the part below every so many seconds. int fraction = second / 5; if (fraction != previous_fraction) { previous_fraction = fraction; } // Run the part below once per minute. if (minute == previous_minute) continue; previous_minute = minute; // Every minute send out queued email, except in client mode. if (!client) tasks_logic_queue (SENDEMAIL); // Check for new mail every five minutes. // Do not check more often with gmail else the account may be shut down. if ((!client) && ((minute % 5) == 0)) { tasks_logic_queue (RECEIVEEMAIL); } // At the nineth minute after every full hour rotate the journal. // The nine is chosen, because the journal rotation will summarize the send/receive messages. // In case send/receive happens every five minutes, it is expected that under normal circumstances // the whole process of sending/receivning will be over, so summarization can then be done. if (minute == 9) tasks_logic_queue (ROTATEJOURNAL); // Client sends/receives Bibles and Consultation. sendreceive_queue_sync (minute); // Sending and receiving Bibles to and from the git repository. // On a production website running on an inexpensive virtual private server // with 512 Mbyte of memory and a fast network connection, // sending and receiving two Bibles takes more than 15 minutes when there are many changes. bool sendreceive = ((hour == 0) && (minute == 5)); bool repeat = ((minute % 5) == 0); if (sendreceive || repeat) { sendreceive_queue_all (sendreceive); } // Deal with the changes in the Bible made per user. // Deal with notifications for the daily changes in the Bibles. // This takes a few minutes on a production machine with two Bibles and changes in several chapters. // It runs in a server configuration, not on a client. if (!client) { if ((hour == 0) && (minute == 20)) { changes_logic_start (); } } // Run the checks on the Bibles. // This takes 15 minutes on a production machine with two Bibles. if (!client) { if ((hour == 0) && (minute == 30)) { checks_logic_start_all (); } } // Database maintenance and trimming. // It takes a few minutes on a production machine. if ((hour == 0) && (minute == 50)) { tasks_logic_queue (MAINTAINDATABASE); } // Export the Bibles to the various output formats. // This may take an hour on a production machine. // This hour was in PHP. In C++ it is much faster. if (!client) { if ((hour == 1) && (minute == 10)) { Export_Logic::scheduleAll (); } } // Delete temporal files older than a few days. if ((hour == 2) && (minute == 0)) { tasks_logic_queue (CLEANTMPFILES); } // Re-index Bibles and notes. // Only update missing indexes. if ((hour == 2) && (minute == 0)) { Database_State::create (); Database_Config_General::setIndexBibles (true); tasks_logic_queue (REINDEXBIBLES); Database_Config_General::setIndexNotes (true); tasks_logic_queue (REINDEXNOTES); } // Actions for a demo installation. if (minute == 10) { if (config_logic_demo_enabled ()) { tasks_logic_queue (CLEANDEMO); } } // Sprint burndown. // It runs every hour in the Cloud. // The script itself determines what to do at which hour of the day or day of the week or day of the month. if (!client) { if (minute == 5) { tasks_logic_queue (SPRINTBURNDOWN); } } // Quit at midnight if flag is set. if (config_globals_quit_at_midnight) { if (hour == 0) { if (minute == 1) { if (!Database_Config_General::getJustStarted ()) { if (tasks_run_active_count ()) { Database_Logs::log ("Server is due to restart itself but does not because of active jobs"); } else { Database_Logs::log ("Server restarts itself"); exit (0); } } } // Clear flag in preparation of restart next minute. // This flag also has the purpose of ensuring the server restarts once during that minute, // rather than restarting repeatedly many times during that minute. if (minute == 0) { Database_Config_General::setJustStarted (false); } } } // Email notes statistics to the users. if (!client) { if ((hour == 3) && (minute == 0)) { tasks_logic_queue (NOTESSTATISTICS); } } // Update SWORD stuff once a week. if (weekday == 1) { // Refresh module list. if ((!client) && (hour == 3) && (minute == 5)) { tasks_logic_queue (REFRESHSWORDMODULES); } // Update installed SWORD modules, shortly after the module list has been refreshed. if ((!client) && (hour == 3) && (minute == 15)) { tasks_logic_queue (UPDATESWORDMODULES); } } // The Cloud updates the list of USFM resources once a week. if (weekday == 1) { if ((!client) && (hour == 3) && (minute == 10)) { tasks_logic_queue (LISTUSFMRESOURCES); } } } catch (exception & e) { Database_Logs::log (e.what ()); } catch (exception * e) { Database_Logs::log (e->what ()); } catch (...) { Database_Logs::log ("A general internal error occurred in the timers"); } } }
// Gets the current number of days since the Unix epoch. int Database_Login::timestamp () { return filter_date_seconds_since_epoch () / 86400; }
string sprint_index (void * webserver_request) { Webserver_Request * request = (Webserver_Request *) webserver_request; Database_Sprint database_sprint; string page; Assets_Header header = Assets_Header (translate("Sprint"), request); header.addBreadCrumb (menu_logic_tools_menu (), menu_logic_tools_text ()); page = header.run (); Assets_View view; if (request->query.count ("previoussprint")) { int month = request->database_config_user()->getSprintMonth (); int year = request->database_config_user()->getSprintYear (); filter_date_get_previous_month (month, year); request->database_config_user()->setSprintMonth (month); request->database_config_user()->setSprintYear (year); } if (request->query.count ("currentprint")) { request->database_config_user()->setSprintMonth (filter_date_numerical_month (filter_date_seconds_since_epoch ())); request->database_config_user()->setSprintYear (filter_date_numerical_year (filter_date_seconds_since_epoch ())); } if (request->query.count ("nextsprint")) { int month = request->database_config_user()->getSprintMonth (); int year = request->database_config_user()->getSprintYear (); filter_date_get_next_month (month, year); request->database_config_user()->setSprintMonth (month); request->database_config_user()->setSprintYear (year); } string bible = access_bible_clamp (webserver_request, request->database_config_user()->getBible ()); int month = request->database_config_user()->getSprintMonth (); int year = request->database_config_user()->getSprintYear (); if (request->post.count ("id")) { string id = request->post ["id"]; string checked = request->post ["checked"]; if (id.length () >= 9) { // Remove "task". id.erase (0, 4); // Convert the fragment to an integer. int identifier = convert_to_int (id); // Find the fragment "box". size_t pos = id.find ("box"); if (pos != string::npos) { // Remove the fragment "box". id.erase (0, pos + 3); // Convert the box to an integer. int box = convert_to_int (id); string categorytext = Database_Config_Bible::getSprintTaskCompletionCategories (bible); vector <string> categories = filter_string_explode (categorytext, '\n'); int category_count = categories.size (); float category_percentage = 100 / category_count; int percentage; bool on = (checked == "true"); if (on) percentage = round ((box + 1) * category_percentage); else percentage = round (box * category_percentage); database_sprint.updateComplete (identifier, percentage); } } return ""; } if (request->post.count ("add")) { string title = request->post ["add"]; database_sprint.storeTask (bible, year, month, title); view.set_variable ("success", translate("New task added")); // Focus the entry for adding tasks only in case a new task was added. view.set_variable ("autofocus", "autofocus"); } if (request->query.count ("mail")) { string mail = request->query ["mail"]; sprint_burndown (bible, true); view.set_variable ("success", translate("The information was mailed to the subscribers")); } if (request->query.count ("bible")) { bible = request->query ["bible"]; if (bible == "") { Dialog_List dialog_list = Dialog_List ("index", translate("Select which Bible to display the Sprint for"), "", ""); vector <string> bibles = access_bible_bibles (request); for (auto & bible : bibles) { dialog_list.add_row (bible, "bible", bible); } page += dialog_list.run(); return page; } else { request->database_config_user()->setBible (bible); } } bible = access_bible_clamp (webserver_request, request->database_config_user()->getBible ()); int id = convert_to_int (request->query ["id"]); if (request->query.count ("remove")) { database_sprint.deleteTask (id); view.set_variable ("success", translate("The task was removed")); } if (request->query.count ("moveback")) { filter_date_get_previous_month (month, year); database_sprint.updateMonthYear (id, month, year); view.set_variable ("success", translate("The task was moved to the previous sprint")); request->database_config_user()->setSprintMonth (month); request->database_config_user()->setSprintYear (year); } if (request->query.count ("moveforward")) { filter_date_get_next_month (month, year); database_sprint.updateMonthYear (id, month, year); view.set_variable ("success", translate("The task was moved to the next sprint")); request->database_config_user()->setSprintMonth (month); request->database_config_user()->setSprintYear (year); } if (request->post.count ("categories")) { string categories = request->post ["categories"]; vector <string> categories2; categories = filter_string_trim (categories); vector <string> vcategories = filter_string_explode (categories, '\n'); for (auto category : vcategories) { category = filter_string_trim (category); if (category != "") categories2.push_back (category); } categories = filter_string_implode (categories2, "\n"); Database_Config_Bible::setSprintTaskCompletionCategories (bible, categories); } view.set_variable ("bible", bible); view.set_variable ("sprint", locale_logic_month (month) + " " + convert_to_string (year)); string categorytext = Database_Config_Bible::getSprintTaskCompletionCategories (bible); view.set_variable ("categorytext", categorytext); vector <string> vcategories = filter_string_explode (categorytext, '\n'); string categories; for (auto category : vcategories) { categories.append ("<td>" + category + "</td>\n"); } view.set_variable ("categories", categories); string tasks; vector <int> vtasks = database_sprint.getTasks (bible, year, month); for (auto & id : vtasks) { string title = filter_string_sanitize_html (database_sprint.getTitle (id)); int percentage = database_sprint.getComplete (id); tasks.append ("<tr id=\"a" + convert_to_string (id) + "\">\n"); tasks.append ("<td><a href=\"?id=" + convert_to_string (id) + "&remove=\">" + emoji_wastebasket () + "</a></td>\n"); tasks.append ("<td></td>\n"); tasks.append ("<td><a href=\"?id=" + convert_to_string (id) + "&moveback=\"> « </a></td>\n"); tasks.append ("<td>" + title + "</td>\n"); int category_count = vcategories.size(); float category_percentage = 100 / category_count; for (size_t i2 = 0; i2 < vcategories.size (); i2++) { int high = round ((i2 + 1) * category_percentage); tasks.append ("<td>\n"); tasks.append ("<input type=\"checkbox\" id=\"task"); tasks.append (convert_to_string (id)); tasks.append ("box"); tasks.append (convert_to_string (i2)); tasks.append ("\""); if (percentage >= high) tasks.append (" checked"); else tasks.append (""); tasks.append (">"); tasks.append ("</td>\n"); } tasks.append ("<td><a href=\"?id=" + convert_to_string (id) + "&moveforward=\"> » </a></td>\n"); tasks.append ("</tr>\n"); } view.set_variable ("tasks", tasks); view.set_variable ("chart", sprint_create_burndown_chart (bible, year, month)); page += view.render ("sprint", "index"); page += Assets_Page::footer (); return page; }
void Database_Logs::rotate () { // Remove the database that was used in older versions of Bibledit. // Since February 2016 Bibledit no longer uses a database for storing the journal. // Reasons that a database is no longer used: // 1. Simpler system. // 2. Android has VACUUM errors due to a locked database. string old_database_file = database_sqlite_file ("logs2"); if (file_exists (old_database_file)) { filter_url_unlink (old_database_file); } // Use a mechanism that handles huge amounts of entries. // The PHP function scandir choked on this or took a very long time. // The PHP functions opendir / readdir / closedir handled it better. // But now, in C++, with the new journal mechanism, this is no longer relevant. string directory = folder (); vector <string> files = filter_url_scandir (directory); // Timestamp for removing older records, depending on whether it's a tiny journal. #ifdef HAVE_TINYJOURNAL int oldtimestamp = filter_date_seconds_since_epoch () - (14400); #else int oldtimestamp = filter_date_seconds_since_epoch () - (6 * 86400); #endif // Limit the available the journal entrie count in the filesystem. // This speeds up subsequent reading of the Journal by the users. // In previous versions of Bibledit, there were certain conditions // that led to an infinite loop, as had been noticed at times, // and this quickly exhausted the available inodes on the filesystem. #ifdef HAVE_TINYJOURNAL int limitfilecount = files.size () - 200; #else int limitfilecount = files.size () - 2000; #endif bool filtered_entries = false; for (unsigned int i = 0; i < files.size(); i++) { string path = filter_url_create_path (directory, files [i]); // Limit the number of journal entries. if ((int)i < limitfilecount) { filter_url_unlink (path); continue; } // Remove expired entries. int timestamp = convert_to_int (files [i].substr (0, 10)); if (timestamp < oldtimestamp) { filter_url_unlink (path); continue; } // Filtering of certain entries. string entry = filter_url_file_get_contents (path); if (journal_logic_filter_entry (entry)) { filtered_entries = true; filter_url_unlink (path); continue; } } if (filtered_entries) { log (journal_logic_filtered_message ()); } }
void sendreceive_resources () { if (sendreceive_resources_watchdog) { int time = filter_date_seconds_since_epoch (); if (time < (sendreceive_resources_watchdog + 900)) { return; } Database_Logs::log ("Resources: " + translate("Watchdog timeout"), Filter_Roles::translator ()); sendreceive_resources_done (); } // If any of the prioritized synchronization tasks run, postpone the current task and do not start it. if (sendreceive_logic_prioritized_task_is_active ()) { sendreceive_resources_done (); this_thread::sleep_for (chrono::seconds (5)); tasks_logic_queue (SYNCRESOURCES); return; } sendreceive_resources_interrupt = false; // If there's nothing to cache, bail out. vector <string> resources = Database_Config_General::getResourcesToCache (); if (resources.empty ()) return; sendreceive_resources_kick_watchdog (); // Error counter. int error_count = 0; // Resource to cache. string resource = resources [0]; // Erase the two older storage locations that were used to cache resources in earlier versions of Bibledit. { Database_OfflineResources database_offlineresources; Database_UsfmResources database_usfmresources; database_offlineresources.erase (resource); database_usfmresources.deleteResource (resource); } Database_Logs::log ("Starting to install resource:" " " + resource, Filter_Roles::consultant ()); Database_Versifications database_versifications; vector <int> books = database_versifications.getMaximumBooks (); for (auto & book : books) { sendreceive_resources_delay_during_prioritized_tasks (); if (sendreceive_resources_interrupt) continue; // Database layout is per book: Create a database for this book. Database_Cache::create (resource, book); // Last downloaded passage in a previous download operation. int last_downloaded_passage = 0; { pair <int, int> progress = Database_Cache::progress (resource, book); int chapter = progress.first; int verse = progress.second; Passage passage ("", book, chapter, convert_to_string (verse)); last_downloaded_passage = filter_passage_to_integer (passage); } // List of passages recorded in the database that had errors on a previous download operation. vector <int> previous_errors; { vector <pair <int, int> > errors = Database_Cache::errors (resource, book); for (auto & element : errors) { int chapter = element.first; int verse = element.second; Passage passage ("", book, chapter, convert_to_string (verse)); int numeric_error = filter_passage_to_integer (passage); previous_errors.push_back (numeric_error); } } string bookName = Database_Books::getEnglishFromId (book); vector <int> chapters = database_versifications.getMaximumChapters (book); for (auto & chapter : chapters) { sendreceive_resources_delay_during_prioritized_tasks (); if (sendreceive_resources_interrupt) continue; bool downloaded = false; string message = resource + ": " + bookName + " chapter " + convert_to_string (chapter); vector <int> verses = database_versifications.getMaximumVerses (book, chapter); for (auto & verse : verses) { sendreceive_resources_delay_during_prioritized_tasks (); if (sendreceive_resources_interrupt) continue; // Numeric representation of passage to deal with. Passage passage ("", book, chapter, convert_to_string (verse)); int numeric_passage = filter_passage_to_integer (passage); // Conditions to download this verse: // 1. The passage is past the last downloaded passage. bool download_verse_past = numeric_passage > last_downloaded_passage; // 2. The passage was recorded as an error in a previous download operation. bool download_verse_error = in_array (numeric_passage, previous_errors); // Whether to download the verse. if (download_verse_past || download_verse_error) { // Fetch the text for the passage. bool server_is_installing_module = false; int wait_iterations = 0; string html, error; do { // Fetch this resource from the server. string address = Database_Config_General::getServerAddress (); int port = Database_Config_General::getServerPort (); // If the client has not been connected to a cloud instance, // fetch the resource from the Bibledit Cloud demo. if (!client_logic_client_enabled ()) { address = demo_address (); port = demo_port (); } string url = client_logic_url (address, port, sync_resources_url ()); url = filter_url_build_http_query (url, "r", filter_url_urlencode (resource)); url = filter_url_build_http_query (url, "b", convert_to_string (book)); url = filter_url_build_http_query (url, "c", convert_to_string (chapter)); url = filter_url_build_http_query (url, "v", convert_to_string (verse)); error.clear (); html = filter_url_http_get (url, error); server_is_installing_module = (html == sword_logic_installing_module_text ()); if (server_is_installing_module) { Database_Logs::log ("Waiting while Bibledit Cloud installs the requested SWORD module"); this_thread::sleep_for (chrono::seconds (60)); wait_iterations++; } } while (server_is_installing_module && (wait_iterations < 5)); // Record the passage as having been done in case it was a regular download, // rather than one to retry a previous download error. if (download_verse_past) Database_Cache::progress (resource, book, chapter, verse); // Clear the registered error in case the verse download corrects it. if (download_verse_error) Database_Cache::error (resource, book, chapter, verse, false); if (error.empty ()) { // Cache the verse data. if (!Database_Cache::exists (resource, book)) Database_Cache::create (resource, book); Database_Cache::cache (resource, book, chapter, verse, html); } else { // Record an error. Database_Cache::error (resource, book, chapter, verse, true); if (message.find (error) == string::npos) { message.append ("; " + error); } error_count++; this_thread::sleep_for (chrono::seconds (1)); } downloaded = true; } sendreceive_resources_kick_watchdog (); } message += "; done"; if (downloaded) Database_Logs::log (message, Filter_Roles::manager ()); } } // Done. if (error_count) { string msg = "Error count while downloading resource: " + convert_to_string (error_count); Database_Logs::log (msg, Filter_Roles::consultant ()); } Database_Logs::log ("Completed installing resource:" " " + resource, Filter_Roles::consultant ()); // In case of too many errors, schedule the resource download again. bool re_schedule_download = false; if (error_count) { if (!sendreceive_resources_interrupt) { re_schedule_download = true; Database_Logs::log ("Errors: Re-scheduling resource installation", Filter_Roles::consultant ()); } } // Store new download schedule. resources = Database_Config_General::getResourcesToCache (); resources = filter_string_array_diff (resources, {resource}); if (re_schedule_download) { resources.push_back (resource); } Database_Config_General::setResourcesToCache (resources); sendreceive_resources_done (); sendreceive_resources_interrupt = false; // If there's another resource waiting to be cached, schedule it for caching. if (!resources.empty ()) tasks_logic_queue (SYNCRESOURCES); }
// This function runs the sprint burndown history logger for $bible. // If no $bible is passed, it will do all Bibles. // If $mail is true, it will mail the burndown chart to the subscribed users. // If $mail is false, it decides on its own whether to mail the chart to the users. void sprint_burndown (string bible, bool email) { int localseconds = filter_date_local_seconds (filter_date_seconds_since_epoch ()); int year = filter_date_numerical_year (localseconds); int month = filter_date_numerical_month (localseconds); int monthday = filter_date_numerical_month_day (localseconds); // 1 to 31. int weekday = filter_date_numerical_week_day (localseconds); // 0 (for Sunday) through 6 (for Saturday). int hour = filter_date_numerical_hour (localseconds); bool sprintstart = false; bool sprintfinish = false; // Every Friday at 2 PM (14:00h) it sends email about the sprint progress. if ((weekday == 5) && (hour == 14)) email = true; // On the first business day of the month, at 10 AM, send email about the start of the sprint. if (filter_date_is_first_business_day_of_month (monthday, weekday) && (hour == 10)) { email = true; sprintstart = true; } // On the last business day of the month, at 2 PM (14:00h), send email about the end of the sprint. if ((monthday == filter_date_get_last_business_day_of_month (year, month)) && (hour == 14)) { email = true; sprintfinish = true; } // Determine what to do, or to quit. if (!email && !sprintstart && !sprintfinish) { if (hour != 1) return; } Database_Logs::log ("Updating Sprint information", Filter_Roles::manager ()); Webserver_Request request; Database_Mail database_mail = Database_Mail (&request); Database_Sprint database_sprint = Database_Sprint (); // Determine year / month / day of the current sprint. // If this script runs from midnight till early morning, // it applies to the day before. // If the script runs during the day, it applies to today. if (hour <= 6) { localseconds -= (3600 * 6); } year = filter_date_numerical_year (localseconds); month = filter_date_numerical_month (localseconds); monthday = filter_date_numerical_month_day (localseconds); // 1 to 31. vector <string> bibles = {bible}; if (bible == "") { bibles = request.database_bibles()->getBibles (); } for (auto bible : bibles) { // Get the total number of tasks for this sprint, // and the average percentage of completion of them, // and store this information in the sprint history table. vector <int> ids = database_sprint.getTasks (bible, year, month); vector <int> percentages; for (auto id : ids) { percentages.push_back (database_sprint.getComplete (id)); } int tasks = ids.size (); int complete = 0; if (tasks != 0) { for (auto percentage : percentages) complete += percentage; complete = round ((float) complete / (float) tasks); } database_sprint.logHistory (bible, year, month, monthday, tasks, complete); // Send email if requested. if (email) { if (tasks) { // Only mail if the current sprint contains tasks. string scategories = Database_Config_Bible::getSprintTaskCompletionCategories (bible); vector <string> categories = filter_string_explode (scategories, '\n'); int category_count = categories.size(); int category_percentage = round (100 / category_count); vector <string> users = request.database_users ()->getUsers (); for (auto user : users) { if (request.database_config_user()->getUserSprintProgressNotification (user)) { string subject = translate("Team's progress in Sprint"); if (sprintstart) subject = translate("Sprint has started"); if (sprintfinish) subject = translate("Sprint has finished"); subject += " | " + bible; vector <string> body; body.push_back ("<h3>" + translate("Sprint Planning and Team's Progress") + " | " + bible + "</h3>"); body.push_back ("<table class='burndown'>"); vector <int> tasks = database_sprint.getTasks (bible, year, month); for (auto id : tasks) { body.push_back ("<tr>"); string title = database_sprint.getTitle (id); body.push_back ("<td>" + title + "</td>"); int complete = database_sprint.getComplete (id); string text; for (int i = 0; i < round (complete / category_percentage); i++) text.append ("▓"); for (int i = 0; i < category_count - round (complete / category_percentage); i++) text.append ("▁"); body.push_back ("<td>" + text + "</td>"); body.push_back ("</tr>"); } body.push_back ("</table>"); body.push_back ("<h3>" + translate("Sprint Burndown Chart - Remaining Tasks") + "</h3>"); string burndownchart = sprint_create_burndown_chart (bible, year, month); body.push_back ("<p>" + burndownchart + "</p>"); if (!body.empty ()) { string mailbody = filter_string_implode (body, "\n"); if (!client_logic_client_enabled ()) database_mail.send (user, subject, mailbody); } } } } else { // Since there are no tasks, no mail will be sent: Make a logbook entry. Database_Logs::log ("No tasks in this Sprint: No email was sent"); } } } }
// 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 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; }
void changes_modifications () { Database_Logs::log ("Change notifications: Generating", Filter_Roles::translator ()); // Notifications are not available to clients for the duration of processing them. config_globals_change_notifications_available = false; // Data objects. Webserver_Request request; Database_Modifications database_modifications; // Check on the health of the modifications database and (re)create it if needed. if (!database_modifications.healthy ()) database_modifications.erase (); database_modifications.create (); // Create online change notifications for users who made changes in Bibles // through the web editor or through a client. // It runs before the team changes. // This produces the desired order of the notifications in the GUI. // At the same time, produce change statistics per user. // Get the users who will receive the changes entered by the contributors. vector <string> recipients; { vector <string> users = request.database_users ()->getUsers (); for (auto & user : users) { if (request.database_config_user ()->getContributorChangesNotificationsOnline (user)) { recipients.push_back (user); } } } // Storage for the statistics. map <string, int> user_change_statistics; float modification_time_total = 0; int modification_time_count = 0; vector <string> users = database_modifications.getUserUsernames (); if (!users.empty ()) Database_Logs::log ("Change notifications: Per user", Filter_Roles::translator ()); for (auto user : users) { // Total changes made by this user. int change_count = 0; // Go through the Bibles changed by the current user. vector <string> bibles = database_modifications.getUserBibles (user); for (auto bible : bibles) { // Body of the email to be sent. string email = "<p>" + translate("You have entered the changes below in a Bible editor.") + " " + translate ("You may check if it made its way into the Bible text.") + "</p>"; size_t empty_email_length = email.length (); // Go through the books in that Bible. vector <int> books = database_modifications.getUserBooks (user, bible); for (auto book : books) { // Go through the chapters in that book. vector <int> chapters = database_modifications.getUserChapters (user, bible, book); for (auto chapter : chapters) { // Get the sets of identifiers for that chapter, and set some variables. vector <Database_Modifications_Id> IdSets = database_modifications.getUserIdentifiers (user, bible, book, chapter); //int referenceOldId = 0; int referenceNewId = 0; int newId = 0; int lastNewId = 0; bool restart = true; // Go through the sets of identifiers. for (auto IdSet : IdSets) { int oldId = IdSet.oldid; newId = IdSet.newid; if (restart) { changes_process_identifiers (&request, user, recipients, bible, book, chapter, referenceNewId, newId, email, change_count, modification_time_total, modification_time_count); //referenceOldId = oldId; referenceNewId = newId; lastNewId = newId; restart = false; continue; } if (oldId == lastNewId) { lastNewId = newId; } else { restart = true; } } // Process the last set of identifiers. changes_process_identifiers (&request, user, recipients, bible, book, chapter, referenceNewId, newId, email, change_count, modification_time_total, modification_time_count); } } // Check whether there's any email to be sent. if (email.length () != empty_email_length) { // Send the user email with the user's personal changes if the user opted to receive it. if (request.database_config_user()->getUserUserChangesNotification (user)) { string subject = translate("Changes you entered in") + " " + bible; if (!client_logic_client_enabled ()) email_schedule (user, subject, email); } } } // Store change statistics for this user. user_change_statistics [user] = change_count; // Clear the user's changes in the database. database_modifications.clearUserUser (user); // Clear checksum cache. request.database_config_user ()->setUserChangeNotificationsChecksum (user, ""); } // Generate the notifications, online and by email, // for the changes in the Bibles entered by anyone since the previous notifications were generated. vector <string> bibles = database_modifications.getTeamDiffBibles (); for (auto bible : bibles) { string stylesheet = Database_Config_Bible::getExportStylesheet (bible); vector <string> changeNotificationUsers; vector <string> users = request.database_users ()->getUsers (); for (auto user : users) { if (access_bible_read (&request, bible, user)) { if (request.database_config_user()->getUserGenerateChangeNotifications (user)) { changeNotificationUsers.push_back (user); } } } users.clear (); // The number of changes processed so far for this Bible. int processedChangesCount = 0; // The files get stored at http://site.org:<port>/revisions/<Bible>/<date> int seconds = filter_date_seconds_since_epoch (); string timepath; timepath.append (convert_to_string (filter_date_numerical_year (seconds))); timepath.append ("-"); timepath.append (filter_string_fill (convert_to_string (filter_date_numerical_month (seconds)), 2, '0')); timepath.append ("-"); timepath.append (filter_string_fill (convert_to_string (filter_date_numerical_month_day (seconds)), 2, '0')); timepath.append (" "); timepath.append (filter_string_fill (convert_to_string (filter_date_numerical_hour (seconds)), 2, '0')); timepath.append (":"); timepath.append (filter_string_fill (convert_to_string (filter_date_numerical_minute (seconds)), 2, '0')); timepath.append (":"); timepath.append (filter_string_fill (convert_to_string (filter_date_numerical_second (seconds)), 2, '0')); string directory = filter_url_create_root_path ("revisions", bible, timepath); filter_url_mkdir (directory); // Produce the USFM and html files. filter_diff_produce_verse_level (bible, directory); // Create online page with changed verses. string versesoutputfile = filter_url_create_path (directory, "changed_verses.html"); filter_diff_run_file (filter_url_create_path (directory, "verses_old.txt"), filter_url_create_path (directory, "verses_new.txt"), versesoutputfile); // Storage for body of the email with the changes. vector <string> email_changes; // Generate the online change notifications. vector <int> books = database_modifications.getTeamDiffBooks (bible); for (auto book : books) { vector <int> chapters = database_modifications.getTeamDiffChapters (bible, book); for (auto chapter : chapters) { Database_Logs::log ("Change notifications: " + bible + " " + filter_passage_display (book, chapter, ""), Filter_Roles::translator ()); string old_chapter_usfm = database_modifications.getTeamDiff (bible, book, chapter); string new_chapter_usfm = request.database_bibles()->getChapter (bible, book, chapter); vector <int> old_verse_numbers = usfm_get_verse_numbers (old_chapter_usfm); vector <int> new_verse_numbers = usfm_get_verse_numbers (new_chapter_usfm); vector <int> verses = old_verse_numbers; verses.insert (verses.end (), new_verse_numbers.begin (), new_verse_numbers.end ()); verses = array_unique (verses); sort (verses.begin (), verses.end()); for (auto verse : verses) { string old_verse_usfm = usfm_get_verse_text (old_chapter_usfm, verse); string new_verse_usfm = usfm_get_verse_text (new_chapter_usfm, verse); if (old_verse_usfm != new_verse_usfm) { processedChangesCount++; // In case of too many change notifications, processing them would take too much time, so take a few shortcuts. string old_html = "<p>" + old_verse_usfm + "</p>"; string new_html = "<p>" + new_verse_usfm + "</p>"; string old_text = old_verse_usfm; string new_text = new_verse_usfm; if (processedChangesCount < 800) { Filter_Text filter_text_old = Filter_Text (bible); Filter_Text filter_text_new = Filter_Text (bible); filter_text_old.html_text_standard = new Html_Text (""); filter_text_new.html_text_standard = new Html_Text (""); filter_text_old.text_text = new Text_Text (); filter_text_new.text_text = new Text_Text (); filter_text_old.addUsfmCode (old_verse_usfm); filter_text_new.addUsfmCode (new_verse_usfm); filter_text_old.run (stylesheet); filter_text_new.run (stylesheet); old_html = filter_text_old.html_text_standard->getInnerHtml (); new_html = filter_text_new.html_text_standard->getInnerHtml (); old_text = filter_text_old.text_text->get (); new_text = filter_text_new.text_text->get (); } string modification = filter_diff_diff (old_text, new_text); database_modifications.recordNotification (changeNotificationUsers, changes_bible_category (), bible, book, chapter, verse, old_html, modification, new_html); string passage = filter_passage_display (book, chapter, convert_to_string (verse)) + ": "; if (old_text != new_text) { email_changes.push_back (passage + modification); } else { email_changes.push_back (translate ("The following passage has no change in the text.") + " " + translate ("The change is in the formatting only.") + " " + translate ("The USFM code is given for reference.")); email_changes.push_back (passage); email_changes.push_back (translate ("Old code:") + " " + old_verse_usfm); email_changes.push_back (translate ("New code:") + " " + new_verse_usfm); } } } // Delete the diff data for this chapter, for two reasons: // 1. New diffs for this chapter can be stored straightaway. // 2. In case of large amounts of diff data, and this function gets killed, // then the next time it runs again, it will continue from where it was killed. database_modifications.deleteTeamDiffChapter (bible, book, chapter); } } // Email the changes to the subscribed users. if (!email_changes.empty ()) { string body; for (auto & line : email_changes) { body.append ("<div>"); body.append (line); body.append ("</div>\n"); } string subject = translate("Recent changes:") + " " + bible; vector <string> users = request.database_users ()->getUsers (); for (auto & user : users) { if (request.database_config_user()->getUserBibleChangesNotification (user)) { if (access_bible_read (&request, bible, user)) { if (!client_logic_client_enabled ()) { email_schedule (user, subject, body); } } } } } } // Index the data and remove expired notifications. Database_Logs::log ("Change notifications: Indexing", Filter_Roles::translator ()); database_modifications.indexTrimAllNotifications (); // Remove expired downloadable revisions. string directory = filter_url_create_root_path ("revisions"); int now = filter_date_seconds_since_epoch (); bibles = filter_url_scandir (directory); for (auto &bible : bibles) { string folder = filter_url_create_path (directory, bible); int time = filter_url_file_modification_time (folder); int days = (now - time) / 86400; if (days > 31) { filter_url_rmdir (folder); } else { vector <string> revisions = filter_url_scandir (folder); for (auto & revision : revisions) { string path = filter_url_create_path (folder, revision); int time = filter_url_file_modification_time (path); int days = (now - time) / 86400; if (days > 31) { filter_url_rmdir (path); Database_Logs::log ("Removing expired downloadable revision notification: " + bible + " " + revision, Filter_Roles::translator ()); } } } } // Clear checksum caches. users = request.database_users ()->getUsers (); for (auto user : users) { request.database_config_user ()->setUserChangeNotificationsChecksum (user, ""); } // Vacuum the modifications index, as it might have been updated. database_modifications.vacuum (); // Make the notifications available again to clients. config_globals_change_notifications_available = true; // Store the statistics in the database. if (modification_time_count) { // Take average timestamp of all timestamps. int timestamp = round (modification_time_total / modification_time_count); for (auto & element : user_change_statistics) { // Store dated change statistics per user. string user = element.first; int count = element.second; Database_Statistics::store_changes (timestamp, user, count); } } Database_Logs::log ("Change notifications: Ready", Filter_Roles::translator ()); }
void sendreceive_changes_kick_watchdog () { sendreceive_changes_watchdog = filter_date_seconds_since_epoch (); }
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 (); }