diff --git a/.gitignore b/.gitignore index 58f7151b6..5ae53173a 100644 --- a/.gitignore +++ b/.gitignore @@ -14,7 +14,7 @@ application/cache/* application/config/database.php application/config/email.php *.bak -logs +logs/*.php cache backup/* system.old diff --git a/api-documentation/catalog-admin/ddi-schema.json b/api-documentation/catalog-admin/ddi-schema.json index a0cf59f51..f99ff1751 100644 --- a/api-documentation/catalog-admin/ddi-schema.json +++ b/api-documentation/catalog-admin/ddi-schema.json @@ -534,10 +534,14 @@ "title":"Keyword", "type":"string" }, + "vocab":{ + "title":"Vocabulary", + "type":"string" + }, "uri":{ "title":"uri", "type":"string" - } + } } } }, diff --git a/api-documentation/catalog-admin/image-schema.json b/api-documentation/catalog-admin/image-schema.json index 4f5d80648..863b5a338 100644 --- a/api-documentation/catalog-admin/image-schema.json +++ b/api-documentation/catalog-admin/image-schema.json @@ -81,34 +81,89 @@ } }, "image_description":{ - "allOf": [{ - "$ref": "../schemas/iptc-pmd-schema.json" - }] - }, - "files": { - "type": "array", - "title": "Files", - "description": "Files", - "items":{ - "type":"object", - "properties":{ - "file_uri": { - "title": "File name", - "description":"File name or URL", - "type": "string" - }, - "format": { - "title": "File format", - "description": "The file format, physical medium, or dimensions of the resource.", - "type": "string" - }, - "note": { - "title": "Notes", - "type": "string" + "type": "object", + "properties": { + "iptc": { + "allOf": [{ "$ref": "../schemas/iptc-pmd-schema.json" }] + }, + "license": { + "type": "array", + "title": "License", + "items": { + "type": "object", + "properties": { + "name": { + "title": "License", + "type": "string" + }, + "uri": { + "title": "URI", + "type": "string" + } + } } }, - "required": ["file_uri"] + "album": { + "type": "array", + "title": "Album", + "items": { + "type": "object", + "properties": { + "name": { + "title": "Name of album", + "type": "string" + }, + "description": { + "title": "Description", + "type": "string" + }, + "owner": { + "title": "Owner", + "type": "string" + }, + "uri": { + "title": "URI", + "type": "string" + } + } + } + }, + "files": { + "type": "array", + "title": "Files", + "description": "Files", + "items":{ + "type":"object", + "properties":{ + "file_uri": { + "title": "File name", + "description":"File name or URL", + "type": "string" + }, + "format": { + "title": "File format", + "description": "The file format, physical medium, or dimensions of the resource.", + "type": "string" + }, + "note": { + "title": "Notes", + "type": "string" + }, + "show": { + "title": "Show file (images only)", + "description": "Show the image file on the page", + "type": "boolean" + } + }, + "required": ["file_uri"] + } + } } } - } + }, + "additional": { + "type": "object", + "description": "Additional metadata", + "properties": {} + } } \ No newline at end of file diff --git a/api-documentation/catalog-admin/script-schema.json b/api-documentation/catalog-admin/script-schema.json index ae0c43a08..f693199d0 100644 --- a/api-documentation/catalog-admin/script-schema.json +++ b/api-documentation/catalog-admin/script-schema.json @@ -11,34 +11,19 @@ "title": "Collection ID that owns the script", "description": "Abbreviation for the collection that owns the script" }, - - "access_policy": { - "type": "string", - "title": "Data access policy", - "description": "Data access policy for attached microdata resources", - "enum": [ - "direct", - "open", - "public", - "licensed", - "remote", - "na" - ], - "default": "na" - }, - "data_remote_url": { - "type": "string", - "title": "Data website URL", - "description": "Link to the website where the data is available, this is only needed if `access_policy` is set to `remote`.", - "default": "" - }, "published": { "type": "integer", "title": "Status", "description": "Status of the script - 0=draft, 1=published", "default": 0 }, + "overwrite": { + "type": "string", + "description": "Overwrite document if already exists?", + "enum":["yes","no"], + "default": "no" + }, "doc_desc": { "type": "object", @@ -147,18 +132,42 @@ }, "production_date": { - "type": "string", "title":"Date of production (YYYY-MM-DD)", - "description": "Date when the project (dissemination-ready version) was implemented" - }, - "geographic_coverage": { - "title": "Geographic coverage", - "description": "Information on the geographic areas (if any) covered by the scripts/project. This may be a list of countries, regions, etc", + "description": "Date when the project (dissemination-ready version) was implemented", "type": "array", "items": { "type": "string" } }, + + "geographic_units": { + "title": "Geographic locations", + "description": "List of geographic units (regions, countries, states, provinces, etc.) for which data are available in the database.", + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "title": "Location name", + "description": "Name of the geographic unit e.g. 'World', 'Africa', 'Afghanistan'", + "type": "string" + }, + "code": { + "title": "Location code", + "description": "Code of the geographic unit (for countries, preferred = ISO3 code)", + "type": "string" + }, + "type": { + "title": "Type", + "description": "Type of geographic unit e.g. country, state, region, province etc", + "type": "string" + } + }, + "required": [ + "name" + ] + } + }, "authoring_entity": { "type": "array", "title": "Authoring entity", @@ -194,9 +203,9 @@ ] } }, - "contributor": { + "contributors": { "type": "array", - "title": "Contributor(s)", + "title": "Contributors", "description": "The person, corporate body, or agency who contributed to the project.", "items": { "type": "object", @@ -233,10 +242,10 @@ ] } }, - "curator": { + "curators": { "type": "array", - "title": "Contributor(s)", - "description": "The person, corporate body, or agency who contributed to the project.", + "title": "Curators", + "description": "The person, corporate body, or agency who curated to the project.", "items": { "type": "object", "properties": { @@ -276,23 +285,144 @@ "type": "string", "title": "Abstract" }, - "output_type": { - "type": "string", - "title":"Output type", - "description": "Type of output of the script/research project. Example: `On-line interactive data visualization`, `Working paper`" + + "keywords":{ + "title":"Keywords", + "type":"array", + "items":{ + "type":"object", + "properties":{ + "name":{ + "title":"Name", + "type":"string" + }, + "vocabulary":{ + "title":"Vocabulary name", + "type":"string" + }, + "uri":{ + "title":"Vocabulary URI", + "type":"string" + } + } + } }, - "publication_url": { - "type": "string", - "title":"Publication URL", - "description": "Link to the publication (output) to which the scripts are related. This will for example be the URL of a PDF working paper." + + "themes":{ + "title":"Themes", + "type":"array", + "items":{ + "type":"object", + "properties":{ + "name":{ + "title":"Name", + "type":"string" + }, + "vocabulary":{ + "title":"Vocabulary name", + "type":"string" + }, + "uri":{ + "title":"Vocabulary URI", + "type":"string" + } + } + } }, - "doi": { - "type": "string", - "title":"DOI", - "description": "DOI handle" + + "topics": { + "type": "array", + "title": "Topics", + "description": "Topics covered by the table (ideally, the list of topics will be a controlled vocabulary)", + "items": { + "type": "object", + "properties": { + "id": { + "title": "Unique Identifier", + "type": "string" + }, + "name": { + "title": "Topic", + "type": "string" + }, + "parent_id": { + "title": "Parent topic Identifier", + "description":"For subtopics, provide the ID of the parent topic", + "type": "string" + }, + "vocabulary": { + "title": "Vocabulary", + "description": "Name of the controlled vocabulary, if the topic is from a taxonomy.", + "type": "string" + }, + "uri": { + "title": "Vocabulary URI", + "description": "Link to the controlled vocabulary web page, if the topic is from a taxonomy.", + "type": "string" + } + }, + "required": [ + "id","name" + ] + } + }, + + "disciplines": { + "type": "array", + "title": "Disciplines", + "description": "Disciplines e.g. `Social sciences, economics`, `Natural sciences, biology`", + "items": { + "type": "object", + "properties": { + "name": { + "title": "Discipline title or name", + "type": "string" + }, + "vocabulary": { + "title": "Vocabulary", + "description": "Vocabulary", + "type": "string" + }, + "uri": { + "title": "URI", + "description": "Website link", + "type": "string" + } + }, + "required": [ + "name" + ] + } + }, + + "output_types":{ + "title":"Output types", + "description": "Type of outputs of the script/research project. Example: `On-line interactive data visualization`, `Working paper`", + "type":"array", + "items":{ + "type":"object", + "properties":{ + "type":{ + "title":"Type", + "type":"string" + }, + "description":{ + "title":"Description", + "type":"string" + }, + "uri":{ + "title":"URI", + "type":"string" + }, + "doi":{ + "title":"DOI", + "type":"string" + } + } + } }, - "repository_url": { + "repository_uri": { "type": "array", "title": "Source code repository", "description": "Source code repository", @@ -318,59 +448,64 @@ "name" ] } - }, + }, + "project_website": { - "type": "string", - "description": "Project website link" + "title":"Project website", + "description": "Project website link", + "type": "array", + "items": { + "type": "string" + } }, + "version_statement": { "type": "object", "title": "Version Statement", "description": "Version Statement", - "_ddi_xpath":"stdyDscr/citation/verStmt", "properties": { "version": { "title": "Version", - "type": "string", - "_ddi_xpath":"stdyDscr/citation/verStmt/version" + "type": "string" }, "version_date": { "title": "Version Date", - "type": "string", - "_ddi_xpath":"stdyDscr/citation/verStmt/version/@date" + "type": "string" }, "version_resp": { "title": "Version Responsibility Statement", "description":"The organization or person responsible for the version of the work", - "type": "string", - "_ddi_xpath":"stdyDscr/citation/verStmt/verResp" + "type": "string" }, "version_notes": { "title": "Version Notes", - "type": "string", - "_ddi_xpath":"stdyDscr/citation/verStmt/notes" + "type": "string" } } }, "language": { - "type": "object", + "type": "array", "title": "Language", "description": "Documentation language e.g. English, French, etc.", - "properties": { - "name": { - "title": "Name", - "type": "string" + "items": { + "type": "object", + "properties": { + "name": { + "title": "Name", + "type": "string" + }, + "code": { + "title": "Code", + "type": "string" + } }, - "code": { - "title": "Code", - "type": "string" - } - }, - "required": [ - "name" - ] + "required": [ + "name" + ] + } }, + "methods": { "type": "array", "title":"Methods or algorithms applied", @@ -440,36 +575,32 @@ "license": { - "type": "object", - "title": "License", - "description": "License", + "type": "array", + "title": "License", + "items": { + "type": "object", "properties": { "name": { - "title": "Name", + "title": "License", "type": "string" }, - "URI": { + "uri": { "title": "URI", "type": "string" } - }, - "required": [ - "name" - ] + } + } }, - - - - "pub_research": { + "review_process": { "type": "array", - "title": "Published research", - "description": "Published research", + "title": "Review process", + "description": "Review process", "items": { "type": "object", "properties": { - "submit_date": { + "submission_date": { "title": "Date submitted", "type": "string" }, @@ -481,63 +612,18 @@ "title": "Review status", "type": "string" }, - "review_date": { - "title": "Review status", - "type": "string" - }, - "approval_date": { - "title": "Approval date", - "type": "string" - }, "approval_authority": { "title": "Approval authority", "type": "string" }, - "pub_date": { - "title": "Date published", + "approval_date": { + "title": "Date of approval", "type": "string" } } - }, - "required": [ - "name" - ] + } }, - - - "data_included": { - "type": "boolean", - "description": "Is data included with the script?" - }, - "data_url": { - "type": "string", - "description": "Link to an external website where data is available" - }, - "contact": { - "type": "array", - "title": "Contact", - "description": "Contact", - "items": { - "type": "object", - "properties": { - "name": { - "title": "Name", - "type": "string" - }, - "affiliation": { - "title": "Affiliation", - "type": "string" - }, - "URI": { - "title": "URI", - "type": "string" - } - } - }, - "required": [ - "name" - ] - }, + "disclaimer": { "title": "Disclaimer", "type": "string" @@ -548,13 +634,13 @@ }, "citation_requirement": { "type": "string", - "description": "Citation requirements" + "description": "Citation requirements" }, - "data_desc": { + "datasets": { "type": "array", - "title": "Data description", - "description": "Contributors", + "title": "Datasets", + "description": "Datasets used by script", "items": { "type": "object", "properties": { @@ -574,8 +660,9 @@ "title": "Data access policy", "type": "string" }, - "URI": { - "title": "URL", + "uri": { + "title": "URI", + "description": "Link to the website", "type": "string" } } @@ -583,48 +670,9 @@ "required": [ "name" ] - }, - - "review_process": { - "type": "array", - "title": "Project Review Process", - "description": "Project review process that led to the publishing of the scripts", - "items": { - "type": "object", - "properties": { - "submit_date": { - "title": "Submission date", - "type": "string" - }, - "reviewer": { - "title": "Reviewer name", - "type": "string" - }, - "status": { - "title": "Status of review", - "type": "string" - }, - "review_date": { - "title": "Date of review", - "type": "string" - }, - "approval_date": { - "title": "Date of final approval", - "type": "string" - }, - "authority": { - "title": "Authority", - "description":"Identification of the person or organization having formally approved the scripts/project after comlpetion of the review process", - "type": "string" - } - } - }, - "required": [ - "reviewer" - ] - }, + }, - "sponsor": { + "sponsors": { "type": "array", "title": "Sponsor / Funding agency", "description": "The source(s) of funds for production of the work. If different funding agencies sponsored different stages of the production process, use the 'role' attribute to distinguish them.", @@ -642,6 +690,10 @@ "role": { "title": "Role", "type": "string" + }, + "grant_no":{ + "title": "Grant number", + "type": "string" } } }, @@ -649,6 +701,7 @@ "name" ] }, + "acknowledgements": { "type": "array", "title": "Other Identifications /Acknowledgments", @@ -732,10 +785,10 @@ }, - "script_files": { + "scripts": { "type": "array", "title": "Script files", - "description": "Script files", + "description": "Description of each script file", "items": { "type": "object", "properties": { diff --git a/api-documentation/catalog-admin/swagger.yaml b/api-documentation/catalog-admin/swagger.yaml index aa9623c83..737ca91bf 100644 --- a/api-documentation/catalog-admin/swagger.yaml +++ b/api-documentation/catalog-admin/swagger.yaml @@ -844,6 +844,31 @@ paths: description: successful operation security: - ApiKeyAuth: [] + /datasets/strip_ddi/{IDNo}/{options}: + put: + tags: + - Survey + summary: Strip DDI elements + description: Remove metadata from the DDI file + operationId: stripDDI + parameters: + - in: "path" + name: IDNo + type: string + description: "Dataset IDNo" + - in: "path" + name: options + type: string + description: Options for removing metadata elements. Valid options are `summary_stats`, `variables`, `keep_basic` + consumes: + - application/json + produces: + - application/json + responses: + '200': + description: successful operation + security: + - ApiKeyAuth: [] /datasets/update_id/{datasetIDNo}/{newId}: put: tags: diff --git a/application/config/config.php b/application/config/config.php index 6148a3ced..0461531ca 100644 --- a/application/config/config.php +++ b/application/config/config.php @@ -231,7 +231,7 @@ | your log files will fill up very fast. | */ -$config['log_threshold'] = 1; +$config['log_threshold'] = 0; /* |-------------------------------------------------------------------------- diff --git a/application/controllers/Auth.php b/application/controllers/Auth.php index 326538f5a..6035f8aa3 100644 --- a/application/controllers/Auth.php +++ b/application/controllers/Auth.php @@ -5,6 +5,7 @@ function __construct() { parent::__construct($skip_auth=TRUE); + $this->load->library('Nada_csrf'); $this->load->library('ion_auth'); $this->load->library('session'); $this->load->library('form_validation'); @@ -18,7 +19,6 @@ function __construct() $this->lang->load('general'); $this->lang->load('users'); - $this->load->model('token_model'); $this->load->driver('captcha_lib'); //$this->output->enable_profiler(TRUE); @@ -70,25 +70,8 @@ function profile() function edit_profile() { $this->disable_page_cache(); - - //check if user is logged in $this->_is_logged_in(); - - //log - $this->db_logger->write_log('profile-edit'); - - //create a form token - if ($this->input->post("form_token")) - { - //use the one in the postback - $this->form_token=$this->input->post("form_token"); - } - else - { - //create a new token - $this->form_token=$this->token_model->create_token(); - } - + $csrf=$this->nada_csrf->generate_token(); //currently logged in user $data['user']= $this->ion_auth->get_user($this->session->userdata('user_id')); @@ -109,14 +92,10 @@ function edit_profile() 'country' => $this->input->post('country'), ); $this->ion_auth->update_user($data['user']->id,$update_data); - - //delete the token so form can't be re-submitted - $this->token_model->remove_token($this->input->post('form_token')); - $this->session->set_flashdata('message', t("profile_updated")); redirect("auth/profile", 'refresh'); } - + $data['csrf']=$csrf; $content=$this->load->view('auth/profile_edit',$data,TRUE); $this->template->write('title', t('edit_profile'),true); @@ -124,6 +103,8 @@ function edit_profile() $this->template->render(); } + + /** * checks if a user is logged in, otherwise redirects to the login page * @@ -243,39 +224,17 @@ function login() function logout() { $this->disable_page_cache(); - $this->data['title'] = t("logout"); - - //log - $this->db_logger->write_log('logout'); - - //log the user out $logout = $this->ion_auth->logout(); - - //redirect them back to the page they came from redirect('', 'refresh'); - } + } + //change password function change_password() { $this->disable_page_cache(); - - //log - $this->db_logger->write_log('change-pass'); - - //create a form token - if ($this->input->post("form_token")) - { - //use the one in the postback - $this->form_token=$this->input->post("form_token"); - } - else - { - //create a new token - $this->form_token=$this->token_model->create_token(); - } - + $csrf=$this->nada_csrf->generate_token(); $use_complex_password=$this->config->item("require_complex_password"); $this->form_validation->set_rules('old', t('old_password'), 'required|max_length[20]|xss_clean'); @@ -285,11 +244,11 @@ function change_password() if (!$this->ion_auth->logged_in()) { redirect('auth/login', 'refresh'); - } + } + $user = $this->ion_auth->get_user($this->session->userdata('user_id')); - if ($this->form_validation->run() == false) //display the form - { + if ($this->form_validation->run() == false){ //set the flash data error message if there is one $this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message'); @@ -310,25 +269,18 @@ function change_password() 'type' => 'hidden', 'value' => $user->id, ); - - //render + $this->data['csrf']=$csrf; $output=$this->load->view('auth/change_password', $this->data,TRUE); $this->template->write('content', $output,true); $this->template->write('title', t('change_password'),true); $this->template->render(); - } - else - { + else{ $identity = $this->session->userdata($this->config->item('identity')); - $change = $this->ion_auth->change_password($identity, $this->input->post('old'), $this->input->post('new')); - //delete the token so form can't be re-submitted - $this->token_model->remove_token($this->input->post('form_token')); - - if ($change) { //if the password was successfully changed + if ($change) { $this->session->set_flashdata('message', t('password_changed_success')); $this->logout(); } @@ -339,6 +291,8 @@ function change_password() } } + + //forgot password function forgot_password() { @@ -450,24 +404,12 @@ function create_user() //create a new user function _create_user() - { - $this->data['title'] = t("register"); - $content=NULL; - - //create a form token - if ($this->input->post("form_token")) - { - //use the one in the postback - $this->form_token=$this->input->post("form_token"); - } - else - { - //create a new token - $this->form_token=$this->token_model->create_token(); - } - - $use_complex_password=$this->config->item("require_complex_password"); + { + $this->data['title'] = t("register"); + $content=NULL; + $use_complex_password=$this->config->item("require_complex_password"); + $csrf=$this->nada_csrf->generate_token(); //validate form input $this->form_validation->set_rules('first_name', t('first_name'), 'trim|required|xss_clean|max_length[50]'); @@ -478,8 +420,9 @@ function _create_user() $this->form_validation->set_rules('country', t('country'), 'trim|xss_clean|max_length[150]|callback_country_valid'); $this->form_validation->set_rules('password', t('password'), 'required|min_length['.$this->config->item('min_password_length').']|max_length['.$this->config->item('max_password_length').']|matches[password_confirm]|is_complex_password['.$use_complex_password.']'); $this->form_validation->set_rules('password_confirm', t('password_confirmation'), 'required'); - $this->form_validation->set_rules('form_token', 'FORM TOKEN', 'trim|callback_validate_token'); - $this->form_validation->set_rules($this->captcha_lib->get_question_field(), t('captcha'), 'trim|required|max_length[15]|callback_validate_captcha'); + //$this->form_validation->set_rules('form_token', 'FORM TOKEN', 'trim|callback_validate_token'); + $this->form_validation->set_rules('csrf_token', 'CSRF TOKEN', 'trim|callback_validate_token'); + $this->form_validation->set_rules($this->captcha_lib->get_question_field(), t('captcha'), 'trim|required|callback_validate_captcha'); if ($this->form_validation->run() === TRUE) { @@ -499,14 +442,7 @@ function _create_user() 'email'=>$email, 'identity'=>$username ); - - //register the user $this->ion_auth->register($username,$password,$email,$additional_data); - - //delete the token so form can't be re-submitted - $this->token_model->remove_token($this->input->post('form_token')); - - //show the success message $content=$this->load->view('auth/create_user_confirm',NULL,TRUE); //notify admins @@ -556,15 +492,18 @@ function _create_user() 'type' => 'password', 'value' => $this->form_validation->set_value('password_confirm'), ); - $content=$this->load->view('auth/create_user', $this->data,TRUE); + $this->data['csrf']=$csrf; + $content=$this->load->view('auth/create_user', $this->data,TRUE); } - //render final output - $this->template->write('content', $content,true); - $this->template->write('title', $this->data['title'],true); - $this->template->render(); + + //render final output + $this->template->write('content', $content,true); + $this->template->write('title', $this->data['title'],true); + $this->template->render(); } + /** * * validate captcha @@ -574,8 +513,7 @@ function validate_captcha() { $output=$this->captcha_lib->check_answer(); - if ($output===FALSE) - { + if ($output===FALSE){ $this->form_validation->set_message('validate_captcha', t('invalid_captcha')); } @@ -584,18 +522,17 @@ function validate_captcha() /** * - * validate form token. avoids duplicate entries + * validate CSRF token * */ - function validate_token($str) - { - $exists=$this->token_model->token_exists($str); - - if ($exists===FALSE) + function validate_token() + { + if (!$this->nada_csrf->validate_token()) { $this->form_validation->set_message('validate_token', t('form_already_saved')); return FALSE; } + return TRUE; } diff --git a/application/controllers/Catalog.php b/application/controllers/Catalog.php index 799223277..80915d2b0 100644 --- a/application/controllers/Catalog.php +++ b/application/controllers/Catalog.php @@ -265,7 +265,7 @@ function _search() $offset= ($search_options->page-1)*$this->limit; //allowed fields for sort_by and sort_order - $allowed_fields = array('proddate','titl','labl','nation','popularity','rank'); + $allowed_fields = array('proddate','title','labl','nation','popularity','rank'); $allowed_order=array('asc','desc'); //set default sort options, if passed values are not valid @@ -856,12 +856,12 @@ function export($format='print') if ($output['search_type']=='variable') { $rows=$output['rows']; - $cols=explode(",",'uid,name,labl,vid,titl,nation'); + $cols=explode(",",'uid,name,labl,vid,title,nation'); } else { $rows=$output['surveys']['rows']; - $cols=explode(",",'id,idno,titl,nation,authenty,year_start,year_end,created,changed'); + $cols=explode(",",'id,idno,title,nation,authoring_entity,year_start,year_end,created,changed'); } //var_dump($output['surveys']);exit; diff --git a/application/controllers/admin/Reports.php b/application/controllers/admin/Reports.php index 0309de57e..4fe8b06f6 100644 --- a/application/controllers/admin/Reports.php +++ b/application/controllers/admin/Reports.php @@ -241,7 +241,7 @@ function _export_to_csv($rows,$filename) header("Cache-Control: public"); header("Content-Description: File Transfer"); - session_cache_limiter("must-revalidate"); + //session_cache_limiter("must-revalidate"); header('Content-Type: text/csv; charset=utf-8'); header('Content-Disposition: attachment; filename="'.$filename.'"'); diff --git a/application/controllers/admin/Repositories.php b/application/controllers/admin/Repositories.php index 75e1dfeab..3f12afad2 100644 --- a/application/controllers/admin/Repositories.php +++ b/application/controllers/admin/Repositories.php @@ -3,6 +3,7 @@ class Repositories extends MY_Controller { var $errors=''; var $search_fields=array('username','email','status'); + var $uploaded_thumbnail_path=''; function __construct() @@ -30,21 +31,9 @@ function __construct() //list repositories function index() - { - //get array of db rows + { $result['rows']=$this->_search(); - - /*$result['rows']=$this->repository_model->get_repositories($published=FALSE, $system=FALSE);// - $repo_sections=$this->repository_model->get_repository_sections(); - - foreach($repo_sections as $section) - { - $result['sections'][$section['id']]=$section['title']; - }*/ - - //load the contents of the page into a variable - $content=$this->load->view('repositories/index-default', $result,true); - + $content=$this->load->view('repositories/index-default', $result,true); $this->template->write('content', $content,true); $this->template->write('title', t('repositories_management'),true); $this->template->render(); @@ -114,7 +103,7 @@ function _search() */ function add() { - $this->edit(); + $this->edit(); } //process thumbnail uploads @@ -129,16 +118,15 @@ private function process_file_uploads($file_name) $this->load->library('upload', $config); $output=array(); - if ( ! $this->upload->do_upload($file_name)) - { + if ( ! $this->upload->do_upload($file_name)){ $error = array('error' => $this->upload->display_errors()); $output=array( 'status'=>'error', - 'data'=>$error + 'data'=>$error, + 'upload_path'=>$config['upload_path'] ); } - else - { + else{ $data = array('upload_data' => $this->upload->data()); $output=array( 'status' =>'success', @@ -149,7 +137,38 @@ private function process_file_uploads($file_name) return $output; } - + /** + * + * + * Callback for collection thumbnail uploads + * + */ + function _thumbnail_upload() + { + if(!empty($_FILES['thumbnail_file']['name'])) { + $thumbnail_storage=$this->config->item('collection_image_path', 'collections'); + + if(!file_exists($thumbnail_storage)){ + $error=t('thumbnail_upload_folder_not_set').': '.$thumbnail_storage; + $this->form_validation->set_message('_thumbnail_upload',$error); + return false; + } + + $fileupload_output=$this->process_file_uploads('thumbnail_file'); + + if($fileupload_output['status']=='success'){ + $this->uploaded_thumbnail_path=$fileupload_output['file_name']; + } + else{ + $error=t('thumbnail_upload_failed').': '. $fileupload_output['data']['error']; + $this->form_validation->set_message('_thumbnail_upload', $error); + return false; + } + } + return true; + } + + /** * Edit repo * @@ -159,9 +178,8 @@ function edit($id=NULL) { $this->load->helper('security'); - if (!is_numeric($id) && $id!==NULL) - { - show_error('Invalid id provided');exit; + if (!is_numeric($id) && $id!==NULL){ + show_error('Invalid ID provided');exit; } //set validation rules @@ -173,13 +191,12 @@ function edit($id=NULL) $this->form_validation->set_rules('thumbnail', t('thumbnail'), 'xss_clean|trim|required'); $this->form_validation->set_rules('section', t('section'), 'xss_clean|trim|max_length[3]|is_natural'); $this->form_validation->set_rules('published', t('published'), 'xss_clean|trim|max_length[1]|is_natural'); + $this->form_validation->set_rules('thumbnailfile', 'thumbnail_upload', 'callback__thumbnail_upload'); - if (is_numeric($id)) - { + if (is_numeric($id)){ $this->page_title=t('edit_repository'); } - else - { + else{ $this->page_title=t('create_repository'); } @@ -202,112 +219,83 @@ function edit($id=NULL) ); //process form - if ($this->form_validation->run() == TRUE) - { + if ($this->form_validation->run() == TRUE){ $options=array( - 'group_da_public'=>0, - 'group_da_licensed'=>0 - ); - $post_arr=$_POST; + 'group_da_public'=>0, + 'group_da_licensed'=>0 + ); + $post_arr=$_POST; - //read post values to pass to db - foreach($post_arr as $key=>$value) - { - $options[$key]=$this->input->post($key); - } - - //sanitize description html - $options['long_text']=$this->sanitize_html_input($options['long_text']); + //read post values to pass to db + foreach($post_arr as $key=>$value){ + $options[$key]=$this->input->post($key); + } - /*echo '
';
-            echo '';
-            die();*/
+			//sanitize description html
+			$options['long_text']=$this->sanitize_html_input($options['long_text']);
 
-				//process thumbnail file uploads
-				if(!empty($_FILES['thumbnail_file']['name'])) 
-				{
-					$fileupload_output=$this->process_file_uploads('thumbnail_file');
-					
-					if($fileupload_output['status']=='success')
-					{
-						//update thumbnail path
-						$options['thumbnail']=$fileupload_output['file_name'];
-					}
-				}
+			//process thumbnail file uploads
+			if(!empty($_FILES['thumbnail_file']['name']) && !empty($this->uploaded_thumbnail_path) ){
+					$options['thumbnail']=$this->uploaded_thumbnail_path;
+			}
 								
-				if ($id==NULL)
-				{
-					$db_result=$this->repository_model->insert($options);
-				}
-				else
-				{
-					//update db
-					$db_result=$this->repository_model->update($id,$options);
-				}
+			if ($id==NULL){
+				$db_result=$this->repository_model->insert($options);
+			}
+			else{
+				//update db
+				$db_result=$this->repository_model->update($id,$options);
+			}
 							
-				if ($db_result===TRUE)
-				{
-					if (isset($options['ispublished']) && is_numeric($id))
-					{
-						//update collection studies status
-						$this->publish($id,$options['ispublished']);
-					}
-				
-					//update successful
-					$this->session->set_flashdata('message', t('form_update_success'));
-					
-					//redirect back to the list
-                    if (!$id) {
-                        redirect("admin/repositories", "refresh");
-                    }
-                    else{
-                        redirect("admin/repositories/edit/" . $id, "refresh");
-                    }
-				}
-				else
-				{
-					//update failed
-					$this->form_validation->set_error(t('form_update_fail'));
-				}
+			if ($db_result===TRUE){
+				/*if (isset($options['ispublished']) && is_numeric($id)){
+					//update collection studies status
+					$this->publish($id,$options['ispublished']);
+				}*/
+			
+				//update successful
+				$this->session->set_flashdata('message', t('form_update_success'));
+				redirect("admin/repositories", "refresh");				
+			}
+			else{
+				//update failed
+				$this->form_validation->set_error(t('form_update_fail'));
+			}
 		}
 		else //first time page is loaded or validation failed
 		{
-				if ($id!=NULL)
-				{
-					$row=$this->repository_model->select_single($id);
-					
-					if(!$row)
-					{
-						show_error('ID was not found');
-					} 	
-					
-					$this->row_data=$row;
-					
-					//validate and clean up thumbnails
-					$default_thumb=$this->config->item('collection_default_thumb', 'collections');					
-					$thumb_ext=explode(".",basename($this->row_data['thumbnail']));
-					
-					$thumb_ext=$thumb_ext[count($thumb_ext)-1];
-					
-					if (!in_array($thumb_ext,array('png','gif','jpg'))){
-						$this->row_data['thumbnail']=$default_thumb;
-					}
+			if ($id!=NULL){
+				$row=$this->repository_model->select_single($id);				
+				
+				if(!$row){
+					show_error('ID was not found');
+				} 	
+				
+				$this->row_data=$row;
+				
+				//validate and clean up thumbnails
+				$default_thumb=$this->config->item('collection_default_thumb', 'collections');					
+				$thumb_ext=explode(".",basename($this->row_data['thumbnail']));
+				
+				$thumb_ext=$thumb_ext[count($thumb_ext)-1];
+				
+				if (!in_array($thumb_ext,array('png','gif','jpg'))){
+					$this->row_data['thumbnail']=$default_thumb;
 				}
-		}			
+			}
+		}
 
 		//textboxes
 		$fields=array('repositoryid','title','url','organization','country','thumbnail','weight');
 		
-		foreach($fields as $field)
-		{
-				$this->data[$field]= array(
-							'name'	=> $field,
-							'id'    => $field,
-							'type'  => 'text',
-							'class' => 'form-control',
-							'value' => $this->form_validation->set_value($field,$this->row_data[$field]));
+		foreach($fields as $field){
+			$this->data[$field]= array(
+				'name'	=> $field,
+				'id'    => $field,
+				'type'  => 'text',
+				'class' => 'form-control',
+				'value' => $this->form_validation->set_value($field,$this->row_data[$field])
+			);
 		}
 		
 		$this->data['type']=$this->form_validation->set_value('type',$this->row_data['type']);
@@ -319,17 +307,13 @@ function edit($id=NULL)
 		//$this->data['group_da_licensed']=$this->form_validation->set_value('group_da_licensed',$this->row_data['group_da_licensed']);
 		$this->data['section']=$this->form_validation->set_value('section',$this->row_data['section']);
 		
-		//show form
 		$content=$this->load->view('repositories/edit',NULL,true);									
-				
-		//pass data to the site's template
 		$this->template->write('content', $content,true);
-		
-		//render final output
 	  	$this->template->render();								
 	}
 
 
+
     /**
      *
      * Validation HTML
diff --git a/application/controllers/api/Datasets.php b/application/controllers/api/Datasets.php
index bb1d26ed2..7336908ae 100644
--- a/application/controllers/api/Datasets.php
+++ b/application/controllers/api/Datasets.php
@@ -1136,37 +1136,10 @@ function reload_ddi_put($id=NULL,$partial=false)
 				throw new Exception("ID_MISSING");
 			}
 
-			$this->load->model("Data_file_model");
-			$this->load->library('DDI2_import');
-
-			//get survey ddi file path by id
-			$ddi_file=$this->Catalog_model->get_survey_ddi_path($id);
-
-			if ($ddi_file===FALSE){
-				throw new Exception("DDI_FILE_NOT_FOUND");
-			}
-			
-			$dataset=$this->dataset_manager->get_row($id);
-
-			$params=array(
-				'file_type'=>'survey',
-				'file_path'=>$ddi_file,
-				'user_id'=>$this->get_api_user_id(),
-				'repositoryid'=>$dataset['repositoryid'],
-				'overwrite'=>'yes',
-				'partial'=>$partial
-			);
-					
-			$result=$this->ddi2_import->import($params,$id);
-
-			//reset changed and created dates
-			$update_options=array(
-				'changed'=>$dataset['changed'],
-				'created'=>$dataset['created'],
-				'repositoryid'=>$dataset['repositoryid']
-			);
 
-			$this->dataset_manager->update_options($id,$update_options);
+			$this->load->library('DDI_Utils');
+			$user_id=$this->get_api_user_id();
+			$result=$this->ddi_utils->reload_ddi($id, $user_id, $partial);
 
 			$output=array(
 				'status'=>'success',
@@ -1301,10 +1274,44 @@ function ddi2array_post()
 				'message'=>$e->getMessage()
 			);
 			$this->set_response($error_output, REST_Controller::HTTP_BAD_REQUEST);
-		}
-
-		
+		}		
 	}
 
-		
+
+
+	/**
+	*
+	* Strip metadata elements from the DDI
+	*
+	* @strip - 'summary_stats', 'variables', 'keep_basic'
+	*
+	**/
+	function strip_ddi_put($idno=NULL,$strip='')
+	{
+		$this->load->library("DDI_Utils");
+
+		try{
+			$sid=$this->get_sid_from_idno($idno);
+			$user_id=$this->get_api_user_id();
+			$result=$this->ddi_utils->strip_ddi($sid, $strip, $keep_original=true);
+
+			if($result){
+				$result=$this->ddi_utils->reload_ddi($sid, $user_id, $partial=false);
+			}
+
+			$output=array(
+				'status'=>'success',
+				'result'=>$result
+			);
+
+			$this->set_response($output, REST_Controller::HTTP_OK);	
+		}
+		catch(Exception $e){
+			$error_output=array(
+				'status'=>'failed',
+				'message'=>$e->getMessage()				
+			);
+			$this->set_response($error_output, REST_Controller::HTTP_BAD_REQUEST);
+		}
+	}
 }
diff --git a/application/controllers/api/Utils.php b/application/controllers/api/Utils.php
new file mode 100644
index 000000000..b66268d29
--- /dev/null
+++ b/application/controllers/api/Utils.php
@@ -0,0 +1,102 @@
+load->helper("date");
+	}
+	
+
+    /**
+     * 
+     * Convert RDF to JSON
+     * 
+     */
+    public function parse_rdf_post()
+    {
+        $this->load->library('RDF_Parser');
+
+        try {
+            $result=$this->upload_file('file');
+            $uploaded_path=$result['full_path'];            
+            $rdf_contents=file_get_contents($uploaded_path);
+            $rdf_array=$this->rdf_parser->parse($rdf_contents);
+
+            if ($rdf_array===FALSE || $rdf_array==NULL){
+                throw new Exception("NO_ENTRIES_FOUND");
+            }
+
+            $rdf_fields=$this->rdf_parser->fields;
+            $rdf_fields['additional']='99';
+
+            $result=array();
+            foreach($rdf_array as $row){
+                $result[]=array_combine(array_keys($rdf_fields), $row);
+            }
+        
+            @unlink($uploaded_path);
+
+            $output=array(
+                'status'=>'success',
+                'entries'=>$result
+            );
+
+            $this->set_response($output, REST_Controller::HTTP_OK);			
+        }
+        catch(Exception $e){
+            $output=array(
+                'status'=>'error',
+                'message'=>$e->getMessage()
+            );
+            $this->set_response($output, REST_Controller::HTTP_BAD_REQUEST);
+        }
+
+        
+    }
+
+
+    /**
+	 * 	
+	 *
+	 * upload file to temp
+	 *
+	 * @file_field_name 	- name of POST file variable
+	 *  
+	 **/ 
+	private function upload_file($file_field_name='file', $allowed_types=array('rdf','xml'))
+	{
+		$temp_upload_folder=get_catalog_root().'/tmp';
+		
+		if (!file_exists($temp_upload_folder)){
+			@mkdir($temp_upload_folder);
+		}
+		
+		if (!file_exists($temp_upload_folder)){
+			throw new Exception('DATAFILES-TEMP-FOLDER-NOT-SET');
+		}
+						
+		//upload class configurations for RDF
+		$config['upload_path'] = $temp_upload_folder;
+		$config['overwrite'] = false;
+		$config['encrypt_name']=true;
+		$config['allowed_types'] = implode("|", $allowed_types);
+		
+		$this->load->library('upload', $config);
+
+		//process uploaded rdf file
+		$upload_result=$this->upload->do_upload($file_field_name);
+
+		if (!$upload_result){
+			$error = $this->upload->display_errors();
+			throw new Exception("RDF_UPLOAD::".$error);
+		}
+
+		return $this->upload->data();		
+	}
+		
+	
+}
diff --git a/application/controllers/utils/packager.php b/application/controllers/utils/packager.php
deleted file mode 100644
index 9ec63ebc1..000000000
--- a/application/controllers/utils/packager.php
+++ /dev/null
@@ -1,702 +0,0 @@
- ]
-*	input: export package file name e.g. citations-12-11-12.json.xml
-*	run: /index.php/utils/packager/import_citations/citations-12-11-12.json.xml
-*
-*	It only imports citations that are linked to surveys found in the target catalog. It
-*	searches for survey IDs in the survey alias table. For inserting/updating citations, it is
-*	required that you add IHSN_ID field to the citation's table. It is safe to re-run the script as 
-*	it would not import duplicate citations when using IHSN_ID field.
-*
-*	Requires a minor update to the CITATIONS_MODEL: add IHSN_ID field to update/insert functions
-*
-*
-*	Dependency/Files:
-*
-*	\models\citations_model.php
-*	\models\packager_model.php
-*	\controllers\utils\packager.php
-*
-*
-*
-*
-* ///////////////////////////////////////////////////////////////////////////////////////
-*	SURVEY Packaging
-* ///////////////////////////////////////////////////////////////////////////////////////
-*
-*	NOTE: script can take very long to finish, so only run from CLI
-*
-*	Create Package [create] 
-*	It creates an individual package folder for each survey and create a .PKG package file 
-*	and copies DDI, RDF and resources listed in the RDF except microdata files.
-*
-*	Output is stored in the backup/packages/[survey-folder]
-*
-*	TODO: create a file to list available packages.
-*
-*
-*	RESTORE Package
-*	restore_study($package_file) restores a single survey package.
-*
-*	TODO: Add survey aliases to the export/import options
-*
-**/
-class Packager extends MY_Controller { 
- 
- 	var $package_folder='';
-	var $log_file='';
- 
-    public function __construct()
-    {
-        parent::__construct($skip_auth=TRUE);
-       	$this->load->model('Packager_model');
-		$this->load->model('Catalog_model');
-		$this->load->model('Citation_model');
-		$this->template->set_template('admin');
-		
-		$this->lang->load("general");
-		$this->lang->load("dashboard");
-		
-		//package folder
-		$this->package_folder='backup/packages';
-		$this->log_file=$this->package_folder.'/log-'.date("M-d-y").'.txt';
-		
-		$this->_write_log('====','===================================================');
-    }
- 
-	function index()
-	{	
-		$data['title']='Packager';
-		
-		//load the contents of the page into a variable
-		$content="Studies packager";
-		
-		//set page title
-		$this->template->write('title', 'data packager',true);
-		$this->template->write('content', $content,true);
-	  	$this->template->render();
-	}
-	
-	
-	//create package
-	function create()
-	{
-		//check requiremnets
-		//$this->_check_requirements();
-	
-		//get all surveys
-		$surveys=$this->Packager_model->get_surveys();
-		$surveys=$this->Packager_model->get_surveys_by_tags('ihsn');
-		
-		$output=array();
-		$packages_list=array();
-		
-		//get resources for each survey
-		foreach($surveys as $survey)
-		{
-			//get survey external resources
-			//$resources=$this->Packager_model->get_resources($survey['id']);
-			
-			$survey_obj=(object)$survey;			
-			//$survey_obj->resources=$resources;
-			
-			$output[]=$survey_obj;
-			
-			$packages_list[]=unix_path($this->package_folder.'/'.md5($survey['surveyid']) );
-		}
-		
-		//list of package files created
-		file_put_contents($this->package_folder.'\package-list-'.date("m-d-y-His").'.txt',json_encode($packages_list));
-
-		//package file
-		$file_name='/package-'.date("m-d-y-His").'.pkg';
-		$file_path=$this->package_folder.$file_name;
-		
-		//save package contents
-		$result=@file_put_contents($file_path, json_encode($output));
-		
-		if (!$result)
-		{
-			show_error("FAILED_TO_WRITE_TO_PACAKE_FILE");
-		}
-		
-		echo $file_name.' created successfully!
'; - echo count($output). ' studies were packaged'; - - //package individual study + files - foreach($surveys as $survey) - { - echo "packaging ".$survey['id']."\r\n"; - $this->package_study($survey['id'],FALSE); - } - - } - - - //package a single study - function package_study($id=NULL,$overwrite=TRUE) - { - if (!is_numeric($id)) - { - show_error("INVALID_STUDY"); - } - - /* - Tasks - - 1. copy DDI - 2. create RDF - 3. copy files defined in RDF - 4. - */ - - //get study info from db - $study=$this->Packager_model->get_survey($id); - - if(!$study) - { - show_error("STUDY_NOT_FOUND"); - } - - set_time_limit(0); - - //get survey folder path - $survey_folder=$this->Catalog_model->get_survey_path_full($id); - - //get study resources - $study['resources']=$this->Packager_model->get_resources($id); - - //start packaging - - //check package folder is created - $study_package_folder=unix_path($this->package_folder.'/'.md5($study['surveyid']) ); - - //set package folder path in - $study['package_path']=$study_package_folder; - - //try create folder - @mkdir($study_package_folder); - - if (!file_exists($study_package_folder)) - { - show_error("STUDY_PACKAGE_FOLDER_NOT_FOUND"); - } - - /////////////////////////////////////////////////////////////////////////////////////// - // 1) create package file - /////////////////////////////////////////////////////////////////////////////////////// - $result=@file_put_contents($study_package_folder.'/package.json',json_encode($study)); - - if (!$result) - { - show_error("FAILED_TO_WRITE_PACKAGE_FILE ".$study_package_folder); - } - - /////////////////////////////////////////////////////////////////////////////////////// - // 2) copy DDI - /////////////////////////////////////////////////////////////////////////////////////// - copy($this->Catalog_model->get_survey_ddi_path($id),unix_path($study_package_folder.'/'.$study['ddifilename'])); - - $this->_write_log('info','ddi_copied::'.$study['ddifilename']); - - /////////////////////////////////////////////////////////////////////////////////////// - // 3) copy external resources except microdata - ////////////////////////////////////////////////////////////////////////////////////// - - foreach($study['resources'] as $resource) - { - $found=false; - - //resource types to exclude from copying - $ignore=array('[dat/micro]','[dat]'); - - //check if resource is to be ignored - foreach($ignore as $keyword) - { - if (stristr($resource['dctype'],$keyword)!='') - { - $found=true; - } - } - - //skip if from ignored list - if ($found) - { - continue; - } - - //full path to resource file - $resource_path=unix_path($survey_folder.'/'.$resource['filename']); - $destination_path=unix_path($study_package_folder.'/'.$resource['filename']); - - //copy resource files - if (file_exists($resource_path) && !is_dir($resource_path)) - { - //echo 'FOUND FILE'. $resource['filename']; - set_time_limit(0); - - if (!$overwrite && file_exists($destination_path)) - { - $this->_write_log('info','skipped_resource::'.$resource['filename']); - continue;//skip file copy if overwrite is set to FALSE - } - - copy($resource_path,$destination_path); - $this->_write_log('error','copied_resource::'.$resource['filename']); - } - } - }//end-func - - - - /** - * - * Restore a study from package - **/ - function restore_study($package_file) - { - $data=@file_get_contents($package_file); - - if (!$data) - { - $this->_write_log('error','restore_study::PACKAGE_NOT_FOUND'); - return FALSE; - } - - $study=json_decode($data); - - if (!$study) - { - $this->_write_log('error','restore_study::FAILED_TO_DECODE'); - return FALSE; - } - - $this->_write_log('codebookid',$study->surveyid); - - //import DDI - $ddi_import_result=$this->_import_ddi($study,$overwrite=TRUE); - - if (!$ddi_import_result) - { - $this->_write_log('error','restore_study::DDI_IMPORT_FAILED'); - return FALSE; - } - - - //Set Survey Options - $options=array( - 'link_da' =>$study->link_da, - 'link_technical' =>$study->link_technical, - 'link_study' =>$study->link_study, - 'link_report' =>$study->link_report, - 'formid' =>$study->formid, - 'published' =>0//$study->published - ); - - //update survey - $this->Packager_model->set_survey_options($study->surveyid,$options); - - //get internal survey id - $id=$this->Packager_model->study_exists($study->surveyid); - - if (!$id) - { - echo 'SURVEY_ID_NOT_FOUND'; - $this->_write_log('error','restore_study::SURVEY_ID_NOT_FOUND'); - return FALSE; - } - - $survey_folder=$this->Catalog_model->get_survey_path_full($id); - - //import Resources - - //but first remove any existing resources for the study - $this->Packager_model->delete_resources($study->surveyid); - - //import resources - $this->Packager_model->import_resources($study->surveyid,$study->resources); - $this->_write_log('info','restore_study::imported resources'); - - - //copy Resource files - foreach($study->resources as $resource) - { - $resource=(array)$resource; - - $resource_path=unix_path($study->package_path.'/'.$resource['filename']); - - if (file_exists($resource_path)) - { - $copy=@copy($resource_path,unix_path($survey_folder.'/'.$resource['filename'])); - if ($copy) - { - $this->_write_log('copied',$resource['filename']); - } - else - { - $this->_write_log('copy-failed',$resource['filename']); - } - } - } - - } - - - function restore_study_test() - { - $path='backup/packages/669f1985dddea5d2818e825031d3727a/package.json'; - - $this->_write_log('import', $path); - $this->restore_study($path); - } - - function restore_all_studies() - { - $path='backup/packages/package-list-12-19-12-141955.txt'; - $content=file_get_contents($path); - $packages=json_decode($content); - - $k=0; - foreach($packages as $package) - { - $k++; - - if ($k>=5) - { - break; - } - - $this->_write_log('import', $package); - $this->restore_study($package.'/package.json'); - } - } - - - - /** - * - * import a DDI from package - **/ - function _import_ddi($study,$overwrite=TRUE) - { - /** - 1) if study already exists, update - 2) if study not found, create new - - **/ - - if ($overwrite==FALSE) - { - $id=$this->Packager_model->study_exists($study->surveyid); - - if ($id) - { - //skip import, study already exists - $this->_write_log('import-skipped', 'Skipping, overwrite is set to FALSE and study exists'); - return FALSE; - } - } - - //load DDI Parser Library - $this->load->library('DDI_Parser'); - $this->load->library('DDI_Import','','DDI_Import'); - - $ddi_file=$study->package_path.'/'.$study->ddifilename; - - if (!file_exists($ddi_file)) - { - show_error("DDI_NOT_FOUND".$ddi_file); - } - - //set file for parsing - $this->ddi_parser->ddi_file=$ddi_file; - - //only available for xml_reader - $this->ddi_parser->use_xml_reader=TRUE; - - //validate DDI file - if ($this->ddi_parser->validate()===false) - { - //log import error - $error= t('invalid_ddi_file').' '.$ddi_file; - $this->_write_log('error', $error); - return FALSE; - } - - //parse ddi to array - $data=$this->ddi_parser->parse(); - - //set the repository where the ddi will be uploaded to - $this->DDI_Import->repository_identifier=$study->repositoryid; - - //import to db - $result=$this->DDI_Import->import($data,$ddi_file,$overwrite); - - if (!$result) - { - $error=is_array($this->DDI_Import->errors) ? implode("
",$this->DDI_Import->errors) : $this->DDI_Import->errors; - $this->_write_log('ddi-import-failed',$error ); - } - - return $result; - } - - function _write_log($type,$message) - { - $content=date('H:i:s')."\t$type\t$message\r\n"; - file_put_contents($this->log_file,$content,FILE_APPEND); - } - - - - /** - * - * Export all citations to json format - **/ - function export_citations() - { - $this->load->model('Citation_model'); - - $output_file=$this->package_folder.'/citations-'.date("m-d-y").'.json.xml'; - - //get all citations - $citations=$this->Packager_model->get_citations_ID_array(); - - //start output - $created=@file_put_contents($output_file,''."\r\n".''); - - if (!$created) - { - show_error("OUTPUT_FILE_WRITE_ERROR"); - } - - $combine_row_count=50; - - $count=0; - $output=''; - $k=0; - - //package each citation - foreach($citations as $row) - { - $count++; - $k++; - set_time_limit(0); - //get citation info - $citation=$this->Citation_model->select_single($row['id']); - - //prepare for saving - $output.=''."\r\n"; - - if ($k>=$combine_row_count) - { - //save to output file - file_put_contents($output_file,$output,FILE_APPEND); - - //reset - $k=0; - $output=''; - - echo 'exported '. $count."\r\n"; - } - } - - if ($output!='') - { - file_put_contents($output_file,$output,FILE_APPEND); - } - - //end - file_put_contents($output_file,'',FILE_APPEND); - - echo "$k records exported"; - } - - function import_citations($filename=NULL) - { - - if (!$filename) - { - show_error("NO_FILE"); - } - - $input_file=APPPATH.'/../backup/packages/'.basename($filename); - - if (!file_exists($input_file)) - { - show_error("NOT_FOUND"); - } - - //initialize the reader - $reader = new XMLReader(); - - //read the xml file - if(!$reader->open($input_file)) - { - show_error("FILE_READING_ERROR"); - return false; - } - - //find citation elements - while ($reader->read() ) - { - if ($reader->nodeType == XMLReader::ELEMENT && $reader->localName == "citation") - { - $this->_import_single_citation($reader->readString()); - } - } - $reader->close(); - } - - - /** - * - * Import a single citation from package - **/ - private function _import_single_citation($citation) - { - $citation=json_decode($citation,TRUE); - /* - echo '
';	
-		var_dump($citation->related_surveys);
-		exit;
-		var_dump(json_decode($citation));
-		echo '
'; - exit; - */ - - if (!is_array($citation['related_surveys']) && count($citation['related_surveys'])<1) - { - //skip citations that are not attached to any surveys - return FALSE; - } - - $related_surveys=array(); - - //find matching survey ID in databse - foreach($citation['related_surveys'] as $related) - { - $survey_found=$this->Packager_model->get_survey_uid($related['surveyid']); - - if ($survey_found) - { - $related_surveys[]=$survey_found; - } - } - - if (count($related_surveys)==0) - { - //skip if the related survey is not found in the database - return FALSE; - } - - //insert/update citation and link to the surveys - $citation_id=$this->Packager_model->update_citation($citation,$related_surveys); - - echo 'updated/inserted: '. $citation_id; - echo '
'; - } - - - /** - * - * Return a list of all surveys from the catalog [published/unpublished] - **/ - function export_survey_list() - { - //array of all surveys found in the catalog - $surveys=$this->Packager_model->get_surveys(); - - //array of all survey aliases - $survey_aliases=$this->Packager_model->get_all_survey_aliases(); - - echo ''; - } - - - function compare_catalogs() - { - $form='
'; - $form.='

Paste list of surveys [export_survey_list] here:

'; - $form.=''; - $form.='
'; - - echo $form; - - $survey=$this->input->post('survey'); - if (!$survey) - { - return; - } - - $rows=explode("\r\n",$survey); - - $surveys=array(); - - //build an array of survey IDs and aliases - foreach($rows as $row) - { - $info=explode(":",$row); - - if (!isset($info[1])) - { - continue;//skip row - } - - $surveys[$info[1]]['surveyid']=$info[1];//codebook id - if (isset($info[2]) && trim($info[2])!='') - { - //aliases - $surveys[$info[1]]['alias'][]=explode(",",$info[2]); - } - } - - //compare surveys - $found=array(); - $notfound=array(); - - foreach($surveys as $survey) - { - $exists=$this->Packager_model->get_survey_uid($survey['surveyid']); - - if ($exists) - { - $found[$exists]=$survey; - } - else - { - $notfound[]=$survey; - } - } - - - - echo '
';
-		var_dump($found);
-	}
-	
-}
-/* End of file packager.php */
-/* Location: ./controllers/utils/packager.php */
\ No newline at end of file
diff --git a/application/core/MY_Lang.php b/application/core/MY_Lang.php
new file mode 100644
index 000000000..8f41d9362
--- /dev/null
+++ b/application/core/MY_Lang.php
@@ -0,0 +1,141 @@
+load($value, $idiom, $return, $add_suffix, $alt_path);
+			}
+
+			return;
+		}
+
+		$langfile = str_replace('.php', '', $langfile);
+
+		if ($add_suffix === TRUE)
+		{
+			$langfile = preg_replace('/_lang$/', '', $langfile).'_lang';
+		}
+
+		$langfile .= '.php';
+
+		if (empty($idiom) OR ! preg_match('/^[a-z_-]+$/i', $idiom))
+		{
+			$config =& get_config();
+			$idiom = empty($config['language']) ? 'english' : $config['language'];
+		}
+
+		if ($return === FALSE && isset($this->is_loaded[$langfile]) && $this->is_loaded[$langfile] === $idiom)
+		{
+			return;
+		}
+
+		// Load the base file, so any others found can override it
+		$basepath = BASEPATH.'language/'.$idiom.'/'.$langfile;
+		if (($found = file_exists($basepath)) === TRUE)
+		{
+			include($basepath);
+		}
+
+		// Do we have an alternative path to look in?
+		if ($alt_path !== '')
+		{
+			$alt_path .= 'language/'.$idiom.'/'.$langfile;
+			if (file_exists($alt_path))
+			{
+				include($alt_path);
+				$found = TRUE;
+			}
+		}
+		else
+		{
+			foreach (get_instance()->load->get_package_paths(TRUE) as $package_path)
+			{
+				$package_path .= 'language/'.$idiom.'/'.$langfile;
+				if ($basepath !== $package_path && file_exists($package_path))
+				{
+					include($package_path);
+					$found = TRUE;
+					break;
+				}
+			}
+		}
+
+		if ($found !== TRUE)
+		{
+			//show_error('Unable to load the requested language file: language/'.$idiom.'/'.$langfile);
+			log_message('error', 'Unable to load the requested language file: language/'.$idiom.'/'.$langfile);
+			return TRUE;
+		}
+
+		if ( ! isset($lang) OR ! is_array($lang))
+		{
+			log_message('error', 'Language file contains no data: language/'.$idiom.'/'.$langfile);
+
+			if ($return === TRUE)
+			{
+				return array();
+			}
+			return;
+		}
+
+		if ($return === TRUE)
+		{
+			return $lang;
+		}
+
+		$this->is_loaded[$langfile] = $idiom;
+		$this->language = array_merge($this->language, $lang);
+
+		log_message('info', 'Language file loaded: language/'.$idiom.'/'.$langfile);
+		return TRUE;
+	}
+
+	
+
+}
diff --git a/application/language/base/breadcrumbs_lang.php b/application/language/base/breadcrumbs_lang.php
index e4b332348..9ff4c559b 100644
--- a/application/language/base/breadcrumbs_lang.php
+++ b/application/language/base/breadcrumbs_lang.php
@@ -1,18 +1,17 @@
-Link or Unlink buttons to link or unlink studies.';
-$lang['copy_studies_to']='Copy studies to ';
-$lang['change_repo']='Switch';
-$lang['repositoryid']='Collection';
-$lang['copy_studies']='Copy studies';
-$lang['transfer_study_ownership']='Transfer study owner';
-$lang['transfer_ownership']='Transfer owner';
-$lang['msg_studies_to_transfer']='Studies that will be transferred';
-$lang['study_owned']='Owned study';
-$lang['study_linked']='Linked study';
-$lang['is_harvested_study']='Harvested study';
-$lang['select_publish_unpublish']='Select to publish/unpublish';
-$lang['publish']='Publish';
-$lang['series']='Series';
-$lang['data_access']='Data access';
-$lang['overwrite_if_exists']='Overwrite if already exists?';
-$lang['sort_by']='Sort results by:';
-$lang['surveyid']='SurveyID';
-$lang['no_related_citations_click_here_to_add']='There are no citations attached to this survey, to add related citations, click here.';
-$lang['max_upload_limit']='Max upload file size:';
-$lang['upload_ddi']='Add study';
-$lang['clear_filter']='Clear filter';
-$lang['countries']='Countries';
-$lang['titl']='Title';
-$lang['study_status']='Study status';
-$lang['all']='All';
-$lang['published']='Published';
-$lang['unpublished']='Unpublished';
-$lang['tags']='Tags';
-$lang['click_to_publish_unpublish']='Click to publish or unpublish';
-
-$lang['pdf_not_generated']='PDF not generated';
-$lang['pdf_uptodate']='PDF is up-to-date';
-$lang['pdf_outdated']='PDF is outdated';
-$lang['metadata_in_pdf']='Metadata in PDF';
-$lang['replace_ddi']='Replace DDI';
-$lang['delete_study']='Delete study';
-$lang['browse_metadata']='Browse metadata';
-$lang['generate_pdf']='Generate PDF';
-$lang['upload_rdf']='Upload RDF';
-$lang['link_resources']='Link resources';
-$lang['export_ddi']='Export DDI';
-$lang['export_rdf']='Export RDF';
-$lang['admin_notes']='Admin notes';
-$lang['reviewer_notes']='Reviewer notes';
-$lang['study_collections']='Display in other collections';
-$lang['study_aliases']='Study aliases';
-
-$lang['study_warnings']='Warnings!';
-$lang['warning_study_has_no_external_resources']='Study has no external resources attached';
-$lang['warning_study_has_no_microdata']='Study has no microdata attached';
-$lang['warning_study_has_no_questionnaire']='Study has no questionnaires attached';
-$lang['warning_study_has_pending_licensed_requests']='Study has pending licensed requests';
-$lang['warning_study_not_published']='Study is not published';
-$lang['warning_study_years_not_set']='Study data collection years are not set';
-$lang['warning_study_has_no_pdf_documentation']='Study metadata documentation in PDF is not generated';
-
-
-$lang['study_no_questionnaire']='Studies with no questionnaire';
-$lang['study_no_datafile']='Studies with no data';
-$lang['filter']='Filter';
-$lang['ID']='ID';
-$lang['collection']='Collection';
-$lang['modified_on']='Modified on';
-$lang['Published']='Published';
-$lang['Survey options']='Survey options';
-$lang['Tags']='Tags';
-$lang['Generate PDF']='Generate PDF';
-$lang['Status']='Status';
-
-$lang['batch_upload_files']='Upload files';
-$lang['clear_import_folder']='Clear import files';
-$lang['central_catalog_short_text']='a para describing central catalog';
-$lang['study_exists_in_other_collection']='Study already exists in collection [%s]. To update the study, you must switch to the collection and upload DDI.';
-
-$lang['type_admin']='Admin notes';
-$lang['type_reviewer']='Reviewer notes';
-$lang['type_public']='Public notes';
-$lang['select_note_type']='Select note type';
-$lang['admin_note']='Admin note';
-$lang['reviewer_note']='Reviewer note';
-$lang['public_note']='Public note';
-
-$lang['add_note']='Add Note';
-$lang['click_on_icon_to_remove_citation']='Click on the icon %s to remove citation';
-$lang['attach_citation']='Attach Citation';
-$lang['js_refreshing_page']='Refreshing page, please wait...';
-
-$lang['remove_from_collection']='Remove';
-$lang['remove_from_collection_description']='Remove this study from this collection.';
-$lang['studies_linked_count']='Studies linked from other collections';
-$lang['notes']='Notes';
-$lang['link_study']='Link';
-$lang['unlink_study']='Unlink';
-$lang['transfer']='Transfer';
-$lang['select_the_repository_from_the_list_below']='Select the collection from the list below to transfer ownership to another collection.';
-$lang['study_metadata_updated']='Study metadata has been refreshed!';
-$lang['refresh_ddi']='Refresh DDI';
-$lang['batch_refresh_ddi']='Batch refresh DDI';
-$lang['ddi_batch_refresh_title']='Batch refresh DDI';
-$lang['btn_refresh']='Refresh DDI';
-$lang['refresh_ddi_description']='Refresh DDI updates the database with the metadata from the DDI.';
-$lang['total_studies_found']='Total studies found';
-$lang['mark_as_featured']='Display as featured study?';
-$lang['msg_study_ownership_has_changed']='Study ownership changed!';
-$lang['replace_ddi_failed_duplicate_study_found']='The catalog contains another study with the same ID';
-$lang['show_selected_only']='Show selected only';
-
+$lang['msg_select_repository']="Select collection";
+$lang['repositories']="Collections";
+$lang['msg_copy_studies']="Click on the Link or Unlink buttons to link or unlink studies.";
+$lang['copy_studies_to']="Copy studies to ";
+$lang['change_repo']="Switch";
+$lang['repositoryid']="Collection";
+$lang['copy_studies']="Copy studies";
+$lang['transfer_study_ownership']="Transfer study owner";
+$lang['transfer_ownership']="Transfer owner";
+$lang['msg_studies_to_transfer']="Studies that will be transferred";
+$lang['study_owned']="Owned study";
+$lang['study_linked']="Linked study";
+$lang['is_harvested_study']="Harvested study";
+$lang['select_publish_unpublish']="Select to publish/unpublish";
+$lang['publish']="Publish";
+$lang['series']="Series";
+$lang['data_access']="Data access";
+$lang['overwrite_if_exists']="Overwrite if already exists?";
+$lang['sort_by']="Sort results by:";
+$lang['surveyid']="SurveyID";
+$lang['no_related_citations_click_here_to_add']="There are no citations attached to this survey, to add related citations, click here.";
+$lang['max_upload_limit']="Max upload file size:";
+$lang['upload_ddi']="Add study";
+$lang['clear_filter']="Clear filter";
+$lang['countries']="Countries";
+$lang['titl']="Title";
+$lang['study_status']="Study status";
+$lang['all']="All";
+$lang['published']="Published";
+$lang['unpublished']="Unpublished";
+$lang['tags']="Tags";
+$lang['click_to_publish_unpublish']="Click to publish or unpublish";
+$lang['pdf_not_generated']="PDF not generated";
+$lang['pdf_uptodate']="PDF is up-to-date";
+$lang['pdf_outdated']="PDF is outdated";
+$lang['metadata_in_pdf']="Metadata in PDF";
+$lang['replace_ddi']="Replace DDI";
+$lang['delete_study']="Delete study";
+$lang['generate_pdf']="Generate PDF";
+$lang['upload_rdf']="Upload RDF";
+$lang['link_resources']="Link resources";
+$lang['export_ddi']="Export DDI";
+$lang['export_rdf']="Export RDF";
+$lang['admin_notes']="Admin notes";
+$lang['reviewer_notes']="Reviewer notes";
+$lang['study_collections']="Display in other collections";
+$lang['study_aliases']="Study aliases";
+$lang['study_warnings']="Warnings!";
+$lang['warning_study_has_no_external_resources']="Study has no external resources attached";
+$lang['warning_study_has_no_microdata']="Study has no microdata attached";
+$lang['warning_study_has_no_questionnaire']="Study has no questionnaires attached";
+$lang['warning_study_has_pending_licensed_requests']="Study has pending licensed requests";
+$lang['warning_study_not_published']="Study is not published";
+$lang['warning_study_years_not_set']="Study data collection years are not set";
+$lang['warning_study_has_no_pdf_documentation']="Study metadata documentation in PDF is not generated";
+$lang['study_no_questionnaire']="Studies with no questionnaire";
+$lang['study_no_datafile']="Studies with no data";
+$lang['filter']="Filter";
+$lang['ID']="ID";
+$lang['collection']="Collection";
+$lang['modified_on']="Modified on";
+$lang['Published']="Published";
+$lang['Survey options']="Survey options";
+$lang['Tags']="Tags";
+$lang['Generate PDF']="Generate PDF";
+$lang['Status']="Status";
+$lang['batch_upload_files']="Upload files";
+$lang['clear_import_folder']="Clear import files";
+$lang['central_catalog_short_text']="a para describing central catalog";
+$lang['study_exists_in_other_collection']="Study already exists in collection [%s]. To update the study, you must switch to the collection and upload DDI.";
+$lang['type_admin']="Admin notes";
+$lang['type_reviewer']="Reviewer notes";
+$lang['type_public']="Public notes";
+$lang['select_note_type']="Select note type";
+$lang['admin_note']="Admin note";
+$lang['reviewer_note']="Reviewer note";
+$lang['public_note']="Public note";
+$lang['add_note']="Add Note";
+$lang['click_on_icon_to_remove_citation']="Click on the icon %s to remove citation";
+$lang['attach_citation']="Attach Citation";
+$lang['js_refreshing_page']="Refreshing page, please wait...";
+$lang['remove_from_collection']="Remove";
+$lang['remove_from_collection_description']="Remove this study from this collection.";
+$lang['studies_linked_count']="Studies linked from other collections";
+$lang['notes']="Notes";
+$lang['link_study']="Link";
+$lang['unlink_study']="Unlink";
+$lang['transfer']="Transfer";
+$lang['select_the_repository_from_the_list_below']="Select the collection from the list below to transfer ownership to another collection.";
+$lang['study_metadata_updated']="Study metadata has been refreshed!";
+$lang['refresh_ddi']="Refresh DDI";
+$lang['batch_refresh_ddi']="Batch refresh DDI";
+$lang['ddi_batch_refresh_title']="Batch refresh DDI";
+$lang['btn_refresh']="Refresh DDI";
+$lang['refresh_ddi_description']="Refresh DDI updates the database with the metadata from the DDI.";
+$lang['total_studies_found']="Total studies found";
+$lang['mark_as_featured']="Display as featured study?";
+$lang['msg_study_ownership_has_changed']="Study ownership changed!";
+$lang['replace_ddi_failed_duplicate_study_found']="The catalog contains another study with the same ID";
+$lang['show_selected_only']="Show selected only";
 $lang['Data available from external repository']="Data available from external repository";
 $lang['Data not available']="Data not available";
-
-/* End of file menu_lang.php */
-/* Location: ./system/language/urdu/menu_lang.php */
\ No newline at end of file
+$lang['error_no_collection_selected']="You have not selected a collection!";
+$lang['confirm_publish_records']="Confirm to publish study?";
+$lang['confirm_publish']="Publish?";
+$lang['attach_citations']="Attach citations";
+$lang['return_to_edit_page']="Return to edit page";
+$lang['attach_related_data']="Attach related";
+$lang['no_related_studies_click_here_to_add']="There are no related studies attached";
+$lang['relationship_type']="Relationship type";
+$lang['draft']="Draft";
+$lang['confirm_unpublish_records']="Are you sure you want to unpublish records?";
+$lang['confirm_unpublish']="Confirm unpublish";
+
+$lang['tab_overview']="Overview";
+$lang['tab_manage_files']="Files";
+$lang['tab_resources']="Resources";
+$lang['tab_citations']="Citations";
+$lang['tab_data_files']="Data files";
+$lang['tab_notes']="Notes";
+$lang['tab_related_data']="Related studies";
+
+
+
+/* End of file catalog_admin_lang.php */
+/* Location: ./application/language/english/catalog_admin_lang.php */
\ No newline at end of file
diff --git a/application/language/base/catalog_search_lang.php b/application/language/base/catalog_search_lang.php
index b097b2999..b00e9c5d8 100644
--- a/application/language/base/catalog_search_lang.php
+++ b/application/language/base/catalog_search_lang.php
@@ -1,4 +1,5 @@
 config/email.php file.";
-
-
-
-
-/* End of file vocabularies_lang.php */
-/* Location: ./system/language/english/vocabularies_lang.php */
\ No newline at end of file
+config/email.php file.";
+$lang['test_email_configurations']="Test email configurations";
+
+
+/* End of file configurations_lang.php */
+/* Location: ./application/language/english/configurations_lang.php */
\ No newline at end of file
diff --git a/application/language/base/da_collection_lang.php b/application/language/base/da_collection_lang.php
index 1d0f2c3b8..db0a3290f 100644
--- a/application/language/base/da_collection_lang.php
+++ b/application/language/base/da_collection_lang.php
@@ -1,19 +1,19 @@
-%d cached files, click here to clear cache.";
-
-$lang['recent_studies'] = "Recently updated studies";
-$lang['logged_in_users'] = "Logged in";
-$lang['anonymous_users'] = "Anonymous users viewing the site";
-$lang['Maintenance'] = "Manage studies";
-$lang['Administrators'] = "Administrators";
-$lang['History'] = "History";
-$lang['Edit'] = "Edit collection";
-$lang['Collection'] = "Collection";
-$lang['collection_contains_n_studies'] = "Collection contains %d studies";
-$lang['catalog_contains_n_studies'] = "Catalog contains %d studies";
-$lang['studies_with_no_data_files'] = "PUF with no data files";
-$lang['studies_with_no_questionnaires'] = "with no questionnaires";
-$lang['owned'] = "Owned";
-$lang['linked'] = "Linked";
-$lang['published'] = "Published";
-$lang['unpublished'] = "Unpublished";
+$lang['dashboard']="Dashboard";
+$lang['nada_news_updates']="NADA News & Updates";
+$lang['users']="Users";
+$lang['database_backup']="Database Backup";
+$lang['cache_files']="Cache Files";
+$lang['report_bug']="Report Bug/Feature/Request";
+$lang['reporter_name']="Name";
+$lang['reporter_email']="Email";
+$lang['subject']="Subject";
+$lang['bug_request_description']="Provide detailed description of the bug/feature";
+$lang['submit']="Submit";
+$lang['user_active']="Active";
+$lang['user_disabled']="Disabled";
+$lang['user_inactive']="Inactive - never logged in";
+$lang['bug_report']="Report Bug or Request a feature";
+$lang['run_database_backup_script']="Run database backup script";
+$lang['no_cache_files_found']="No cache files were found";
+$lang['clear_cache_files']="You have %d cached files, click here to clear cache.";
+$lang['recent_studies']="Recently updated studies";
+$lang['logged_in_users']="Logged in";
+$lang['anonymous_users']="Anonymous users viewing the site";
+$lang['Maintenance']="Manage studies";
+$lang['Administrators']="Administrators";
+$lang['History']="History";
+$lang['Edit']="Edit collection";
+$lang['Collection']="Collection";
+$lang['collection_contains_n_studies']="Collection contains %d studies";
+$lang['catalog_contains_n_studies']="Catalog contains %d studies";
+$lang['studies_with_no_data_files']="PUF with no data files";
+$lang['studies_with_no_questionnaires']="with no questionnaires";
+$lang['owned']="Owned";
+$lang['linked']="Linked";
+$lang['published']="Published";
+$lang['unpublished']="Unpublished";
 
 /* End of file dashboard_lang.php */
-/* Location: ./system/language/english/dashboard_lang.php */
\ No newline at end of file
+/* Location: ./application/language/english/dashboard_lang.php */
\ No newline at end of file
diff --git a/application/language/base/data_enclave_lang.php b/application/language/base/data_enclave_lang.php
index a531aab78..2c9ad4883 100644
--- a/application/language/base/data_enclave_lang.php
+++ b/application/language/base/data_enclave_lang.php
@@ -1,7 +1,7 @@
-The National Data Enclave (NDE) was established by the National Data Archive to
+$lang['data_enclave_access_request']="National Data Enclave Access Request";
+$lang['data_enclave_description']="

The National Data Enclave (NDE) was established by the National Data Archive to allow researchers meeting certain qualifications, and under strict supervision, to access confidential statistical micro data files. NDE provides a mechanism whereby researchers can access detailed data files in a secure environment, without @@ -12,9 +12,8 @@

NDE Operations

Researchers can access the data on-site, where they are provided with the data, - computer equipment, software, office space, and NDE staff supervision.

'; - -$lang['data_enclave_application_form_link'] = "Click here to download the Application form for access to data enclave"; + computer equipment, software, office space, and NDE staff supervision.

"; +$lang['data_enclave_application_form_link']="Click here to download the Application form for access to data enclave"; /* End of file data_enclave_lang.php */ -/* Location: ./system/language/english/data_enclave_lang.php */ \ No newline at end of file +/* Location: ./application/language/english/data_enclave_lang.php */ \ No newline at end of file diff --git a/application/language/base/ddi_fields_lang.php b/application/language/base/ddi_fields_lang.php new file mode 100644 index 000000000..861aafdd5 --- /dev/null +++ b/application/language/base/ddi_fields_lang.php @@ -0,0 +1,290 @@ +%s variables, if the system can't generate the PDF, try excluding the 'Data Dictionary Description' option."; -$lang['include_variable_toc'] = "Variable list"; -$lang['include_variable_desc'] = "Variable description"; -$lang['include_external_resources'] = "External resource"; -$lang['Report options'] = "Report options:"; -$lang['processing_pdf_report'] = "Generating PDF report, it may take few minutes or longer..."; - -$lang['get_microdata'] = "Get Microdata"; -$lang['study_description'] = "Study Description"; -$lang['data_dictionary'] = "Data Description"; -$lang['related_materials'] = "Documentation"; -$lang['related_citations'] = "Related Publications"; -$lang['citations'] = "Citations"; -$lang['review_study'] = "Review"; -$lang['add_note'] = "Add note"; -$lang['no_reviewer_notes_found'] = "The study has no reviewer notes attached. To add a new note, use the 'Add note' link."; - -$lang['no_resources_attached'] = "Study has no external resources."; -$lang['no_microdata_attached'] = "Study has no microdata available."; - - - -$lang['created_on'] = "Created on"; -$lang['last_modified'] = "Last modified"; -$lang['page_views'] = "Page views"; -$lang['downloads'] = "Downloads"; -$lang['documentation_in_pdf'] = "Documentation in PDF"; -$lang['download_rdf'] = "Download RDF"; - -$lang['reviewer_notes'] = "Reviewer notes"; -$lang['js_refreshing_page'] = "Reloading page, please wait..."; -$lang['visit_data_catalog_at'] = "Visit our data catalog at"; -$lang['report_generated_on'] = "Report generated on"; - - - -$lang['cover'] = "Cover"; -$lang['study_title'] = "Study Title"; -$lang['overview'] = "Overview"; -$lang['sampling'] = "Sampling"; -$lang['questionnaires'] = "Questionnaires"; -$lang['data_collection'] = "Data Collection"; -$lang['data_processing'] = "Data Processing"; -$lang['data_appraisal'] = "Data Appraisal"; -$lang['file_description'] = "File Description"; -$lang['variable_list'] = "Variable List"; -$lang['variable_description'] = "Variable Description"; -$lang['external_resources'] = "External Resources"; - -$lang['report_lang'] = "Report language"; -$lang['external_resources'] = "External Resources"; -$lang['generate_pdf'] = "Generate PDF"; - -$lang['Mean'] = "Mean"; -$lang['Standard deviation'] = "Standard deviation"; -$lang['search_data_dictionary'] = "Search data dictionary"; -$lang['Total variables(s)'] = "Total variables(s)"; -$lang['download_study_rdf'] = "Download study resource descriptions (e.g. reports, questionnaires, technical documents) in Dublin Core RDF format"; -$lang['download_study_ddi'] = "Download study metadata in DDI (XML) format"; - -$lang['study_documentation_text'] = "Download the questionnaires, technical documents and reports that describe the survey process and the key results for this study."; -$lang['study_description_text'] = "The section provides a detailed description of the study (i.e. the metadata). Topics covered relate to the survey methodology, sampling methods, data collection, funding, dates of collection, geographical coverage and the access policy for the data from this study. Download the metadata in a number of formats from the Export metadata link."; -$lang['data_description_text'] = "This section provides detailed information on the unit-record data generated by this study. This includes a detailed description of the contents of each data file and all the variables within each file. Variables may contain the recorded results of a direct question asked, or be derived in some way. The number of variables and the number of data points (cases) are summarized for each variable."; -$lang['related_publications_text'] = "The data from this study are used in the following publications:"; - - - +$lang['request_microdata']="Request Microdata"; +$lang['download_metadata']="Metadata in XML"; +$lang['website_title']="Website title"; +$lang['study_title']="Study Title"; +$lang['publisher']="Publisher"; +$lang['website_url']="Website URL"; +$lang['study_contains_too_many_variables']="The study contains over %s variables, if the system can't generate the PDF, try excluding the 'Data Dictionary Description' option."; +$lang['include_variable_toc']="Variable list"; +$lang['include_variable_desc']="Variable description"; +$lang['include_external_resources']="External resource"; +$lang['Report options']="Report options:"; +$lang['processing_pdf_report']="Generating PDF report, it may take few minutes or longer..."; +$lang['get_microdata']="Get Microdata"; +$lang['study_description']="Study Description"; +$lang['data_dictionary']="Data Description"; +$lang['related_materials']="Documentation"; +$lang['related_citations']="Related Publications"; +$lang['citations']="Citations"; +$lang['review_study']="Review"; +$lang['add_note']="Add note"; +$lang['no_reviewer_notes_found']="The study has no reviewer notes attached. To add a new note, use the 'Add note' link."; +$lang['no_resources_attached']="Study has no external resources."; +$lang['no_microdata_attached']="Study has no microdata available."; +$lang['created_on']="Created on"; +$lang['last_modified']="Last modified"; +$lang['page_views']="Page views"; +$lang['downloads']="Downloads"; +$lang['documentation_in_pdf']="Documentation in PDF"; +$lang['download_rdf']="Download RDF"; +$lang['reviewer_notes']="Reviewer notes"; +$lang['js_refreshing_page']="Reloading page, please wait..."; +$lang['visit_data_catalog_at']="Visit our data catalog at"; +$lang['report_generated_on']="Report generated on"; +$lang['cover']="Cover"; +$lang['file_description']="File Description"; +$lang['variable_list']="Variable List"; +$lang['variable_description']="Variable Description"; +$lang['external_resources']="External Resources"; +$lang['report_lang']="Report language"; +$lang['generate_pdf']="Generate PDF"; +$lang['Mean']="Mean"; +$lang['Standard deviation']="Standard deviation"; +$lang['search_data_dictionary']="Search data dictionary"; +$lang['Total variables(s)']="Total variables(s)"; +$lang['download_study_rdf']="Download study resource descriptions (e.g. reports, questionnaires, technical documents) in Dublin Core RDF format"; +$lang['download_study_ddi']="Download study metadata in DDI (XML) format"; +$lang['study_documentation_text']="Download the questionnaires, technical documents and reports that describe the survey process and the key results for this study."; +$lang['study_description_text']="The section provides a detailed description of the study (i.e. the metadata). Topics covered relate to the survey methodology, sampling methods, data collection, funding, dates of collection, geographical coverage and the access policy for the data from this study. Download the metadata in a number of formats from the Export metadata link."; +$lang['data_description_text']="This section provides detailed information on the unit-record data generated by this study. This includes a detailed description of the contents of each data file and all the variables within each file. Variables may contain the recorded results of a direct question asked, or be derived in some way. The number of variables and the number of data points (cases) are summarized for each variable."; +$lang['related_publications_text']="The data from this study are used in the following publications:"; +$lang['related_studies']="Related studies"; /* End of file ddibrowser_lang.php */ -/* Location: ./system/language/english/ddibrowser_lang.php */ \ No newline at end of file +/* Location: ./application/language/english/ddibrowser_lang.php */ \ No newline at end of file diff --git a/application/language/base/direct_access_terms_lang.php b/application/language/base/direct_access_terms_lang.php index 9591e61a1..4a12c3b90 100644 --- a/application/language/base/direct_access_terms_lang.php +++ b/application/language/base/direct_access_terms_lang.php @@ -1,11 +1,7 @@ -
  • The data and other materials provided by the National Data Archive will not be redistributed or sold to other individuals, institutions, or organizations @@ -34,9 +30,8 @@ Archive will conform to widely-accepted standards of practice and legal restrictions that are intended to protect the confidentiality of respondents.

    "; - -$lang['form_removed_and_not_available']='Form has been removed and is not longer available.'; -$lang['survey_data_files']='Survey Data Files'; +$lang['form_removed_and_not_available']="Form has been removed and is not longer available."; +$lang['survey_data_files']="Survey Data Files"; /* End of file direct_access_terms_lang.php */ -/* Location: ./system/language/english/direct_access_terms_lang.php */ \ No newline at end of file +/* Location: ./application/language/english/direct_access_terms_lang.php */ \ No newline at end of file diff --git a/application/language/base/fields_document_lang.php b/application/language/base/fields_document_lang.php new file mode 100644 index 000000000..e61cb008c --- /dev/null +++ b/application/language/base/fields_document_lang.php @@ -0,0 +1,78 @@ +%s extension is not enabled. Edit php.ini file to enable extension.'; - -$lang['folder_permissions'] = "Folder READ/WRITE/DELETE permissions"; -$lang['folder'] = "Folder"; -$lang['read_write'] = "Read/Write"; -$lang['delete'] = "Delete"; - -$lang['server_information'] = "Server information"; -$lang['php_version'] = "PHP version"; -$lang['db_version'] = "DB version"; -$lang['connection_success'] = "connection was successful!"; -$lang['web_server'] = "Web server"; -$lang['database_error_cant_continue'] = "The database connection failed, Installer cannot continue until database settings are fixed."; - -$lang['other_php_settings'] = "Other PHP.INI Settings"; -$lang['setting'] = "Setting"; -$lang['value'] = "Value"; -$lang['recommended'] = "Recommended"; -$lang['enabled'] = "Enabled"; -$lang['disabled'] = "Disabled"; - -$lang['install_database'] = "Install Database"; -$lang['create_user'] = "Create account"; -$lang['installer_title'] = "NADA Installer"; -$lang['time_zone_is_required'] = "See how to configure and select the right timezone"; -$lang['not_set'] = "Not set"; +$lang['create_admin_account']="Create administrator account"; +$lang['database_connection_failed']="Database connection failed. Check your database settings."; +$lang['database_creation_failed']="Failed to create the database."; +$lang['database_tables_created']="Database and Tables were created successfully!"; +$lang['return_to_site']="Click here to return to the site home page"; +$lang['page_not_found']="PAGE NOT FOUND"; +$lang['install_completed']="Installation completed!"; +$lang['install_completed_tasks_summary']="The application installation has completed, the summary of the tasks is below:"; +$lang['task']="Task"; +$lang['status']="Status"; +$lang['database']="Database"; +$lang['tables']="Tables"; +$lang['admin_account']="Admin account"; +$lang['click_here_to_launch_application']="Click here to launch the website!"; +$lang['optional']="(optional)"; +$lang['required_php_extensions']="Required PHP Extensions"; +$lang['extensions']="Extensions"; +$lang['enabled']="Enabled"; +$lang['extension_not_enabled']="%s extension is not enabled. Edit php.ini file to enable extension."; +$lang['folder_permissions']="Folder READ/WRITE/DELETE permissions"; +$lang['folder']="Folder"; +$lang['read_write']="Read/Write"; +$lang['delete']="Delete"; +$lang['server_information']="Server information"; +$lang['php_version']="PHP version"; +$lang['db_version']="DB version"; +$lang['connection_success']="connection was successful!"; +$lang['web_server']="Web server"; +$lang['database_error_cant_continue']="The database connection failed, Installer cannot continue until database settings are fixed."; +$lang['other_php_settings']="Other PHP.INI Settings"; +$lang['setting']="Setting"; +$lang['value']="Value"; +$lang['recommended']="Recommended"; +$lang['disabled']="Disabled"; +$lang['install_database']="Install Database"; +$lang['create_user']="Create account"; +$lang['installer_title']="NADA Installer"; +$lang['time_zone_is_required']="See how to configure and select the right timezone"; +$lang['not_set']="Not set"; /* End of file install_lang.php */ -/* Location: ./system/language/english/install_lang.php */ \ No newline at end of file +/* Location: ./application/language/english/install_lang.php */ \ No newline at end of file diff --git a/application/language/base/iso19139_fields_lang.php b/application/language/base/iso19139_fields_lang.php new file mode 100644 index 000000000..37479bce8 --- /dev/null +++ b/application/language/base/iso19139_fields_lang.php @@ -0,0 +1,35 @@ +This form must be filled and submitted by the Lead Researcher. Lead Researcher refers to +$lang['Line ministry/public administration']="Line ministry/public administration"; +$lang['University']="University"; +$lang['Research centre']="Research centre"; +$lang['Private company']="Private company"; +$lang['International organization']="International organization"; +$lang['Non-governmental agency (national)']="Non-governmental agency (national)"; +$lang['Non-governmental agency (international)']="Non-governmental agency (international)"; +$lang['Other']="Other"; +$lang['application_access_licensed_dataset']="Application for Access to a Licensed Dataset"; +$lang['required_fields']="Fields marked with * are mandatory."; +$lang['info_kept_confidential']="The information provided on this page will be kept confidential and will be used for internal purposes only."; +$lang['dataset_requested']="Dataset requested:"; +$lang['filled_lead_research']="

    This form must be filled and submitted by the Lead Researcher. Lead Researcher refers to the person who serves as the main point of contact for all communications involving this agreement. Access to licensed datasets will only be granted when the Lead Researcher is an employee of a legally registered receiving agency (university, company, research centre, national or international organization, etc.) on behalf of @@ -28,38 +23,34 @@ who may decide to approve the request, to deny access to the data, or to request additional information from the Lead Researcher. A signed copy of this request form may also be requested.

    -

    This request is submitted on behalf of:

    '; - -$lang['receiving_org']='Receiving Organization name:'; -$lang['rec_org_refers']='Receiving Organization refers to the organization/university/establishment which employs the Lead Researcher.'; -$lang['org_type']='Organization Type'; -$lang['other']='If other, specify:'; -$lang['post_add']='Postal address'; -$lang['telephone']='Telephone (with country code)'; -$lang['fax']='Fax (with country code)'; -$lang['intended_use']='Intended use of the data:'; -$lang['provide_short_desc']='Please provide a short description of your research project (project question, objectives, methods, expected outputs, partners)'; -$lang['expected_output']='List of expected output(s) and dissemination policy'; -$lang['expected_completion']='Expected completion date (DD-MM-YYYY) of the research project:'; -$lang['data_matching']='Data matching'; -$lang['merge_dataset']='Will you need to merge the dataset with other data?'; -$lang['other_data_merge']='If YES specify all other datasets that will need to be merged'; -$lang['research_team']='Research team members (other than the Lead Researcher)'; -$lang['provide_names']='Provide names, titles, and affiliations of any other members of the research team who will have access to the restricted data.'; -$lang['ident_needed']='Identification of data files and variables needed'; - -$lang['da_website']='The Data Archive provides detailed metadata on its website, including a description of +

    This request is submitted on behalf of:

    "; +$lang['receiving_org']="Receiving Organization name:"; +$lang['rec_org_refers']="Receiving Organization refers to the organization/university/establishment which employs the Lead Researcher."; +$lang['org_type']="Organization Type"; +$lang['other']="If other, specify:"; +$lang['post_add']="Postal address"; +$lang['telephone']="Telephone (with country code)"; +$lang['fax']="Fax (with country code)"; +$lang['intended_use']="Intended use of the data:"; +$lang['provide_short_desc']="Please provide a short description of your research project (project question, objectives, methods, expected outputs, partners)"; +$lang['expected_output']="List of expected output(s) and dissemination policy"; +$lang['expected_completion']="Expected completion date (DD-MM-YYYY) of the research project:"; +$lang['data_matching']="Data matching"; +$lang['merge_dataset']="Will you need to merge the dataset with other data?"; +$lang['other_data_merge']="If YES specify all other datasets that will need to be merged"; +$lang['research_team']="Research team members (other than the Lead Researcher)"; +$lang['provide_names']="Provide names, titles, and affiliations of any other members of the research team who will have access to the restricted data."; +$lang['ident_needed']="Identification of data files and variables needed"; +$lang['da_website']="The Data Archive provides detailed metadata on its website, including a description of data files and variables for each dataset. Researchers who do not need access to the whole dataset may indicate which subset of variables or cases they are interested in. As this reduces the disclosure risk, providing us -with such information may increase the probability that the data will be provided.'; - -$lang['this_request']='This request if submitted to access:'; -$lang['whole_dataset']='The whole dataset (all files, all cases)'; -$lang['subset_data']='A subset of variables and/or cases as described below (note that variables such as the sample weighting coefficients and records identifiers will always be included in subsets):'; -$lang['data_access_agreement']='Data access agreement'; -$lang['i_read_and_agree']='I have read and agree with the conditions'; - -$lang['agreement_text']='

    The representative of the Receiving Organization agrees to comply with the following conditions:

    +with such information may increase the probability that the data will be provided."; +$lang['this_request']="This request if submitted to access:"; +$lang['whole_dataset']="The whole dataset (all files, all cases)"; +$lang['subset_data']="A subset of variables and/or cases as described below (note that variables such as the sample weighting coefficients and records identifiers will always be included in subsets):"; +$lang['data_access_agreement']="Data access agreement"; +$lang['i_read_and_agree']="I have read and agree with the conditions"; +$lang['agreement_text']="

    The representative of the Receiving Organization agrees to comply with the following conditions:

    1. Access to the restricted data will be limited to the Lead Researcher and other members of the research team listed in this request.
    2. Copies of the restricted data or any data created on the basis of the original data will not be copied or made available to anyone other than those mentioned in this Data Access Agreement, unless formally authorized by the Data Archive.
    3. @@ -75,12 +66,13 @@
    4. If there are any changes to the project specification, security arrangements, personnel or organization detailed in this application form, it is the responsibility of the Lead Researcher to seek the agreement of the Data Archive to these changes. Where there is a change to the employer organization of the Lead Researcher this will involve a new application being made and termination of the original project.
    5. Breaches of the agreement will be taken seriously and the Data Archive will take action against those responsible for the lapse if willful or accidental. Failure to comply with the directions of the Data Archive will be deemed to be a major breach of the agreement and may involve recourse to legal proceedings. The Data Archive will maintain and share with partner data archives a register of those individuals and organizations which are responsible for breaching the terms of the Data Access Agreement and will impose sanctions on release of future data to these parties.
    6. -
    '; +"; +$lang['success_request_submitted']="You have successfully submitted the request for data access. A confirmation email has been sent to your email address."; +$lang['track_status_request']="To track the status of your request, visit"; +$lang['thank_you']="Thank you!"; +$lang['confirmation_application_for_licensed_dataset']="[confirmation] Application for Access to a Licensed Dataset"; +$lang['view_all_requests']="View all requests"; +$lang['open_in_new_window']="Open in new window"; -$lang['success_request_submitted']='You have successfully submitted the request for data access. A confirmation email has been sent to your email address.'; -$lang['track_status_request']='To track the status of your request, visit'; -$lang['thank_you']='Thank you!'; -$lang['confirmation_application_for_licensed_dataset']='[confirmation] Application for Access to a Licensed Dataset'; -$lang['view_all_requests']='View all requests'; -$lang['open_in_new_window']='Open in new window'; -?> +/* End of file licensed_access_form_lang.php */ +/* Location: ./application/language/english/licensed_access_form_lang.php */ \ No newline at end of file diff --git a/application/language/base/licensed_request_lang.php b/application/language/base/licensed_request_lang.php index d79d8b77d..3be4260cc 100644 --- a/application/language/base/licensed_request_lang.php +++ b/application/language/base/licensed_request_lang.php @@ -1,156 +1,127 @@ -%s] has been reviewed. To view the review outcome, please visit:"; -//admin_notification_email -$lang['user_has_requested_licensed'] = "The user %s has requested access to a licensed survey %s."; -$lang['to_view_request_instructions'] = "To view the request, login to the NADA site administration and visit the 'Licensed survey requests' page."; -//request_form_view -$lang['received_licensed_request'] = "The %s has received your request for the licensed datafiles. We will notify you via email once your application has been reviewed."; +%s] has been reviewed. To view the review outcome, please visit:"; +$lang['user_has_requested_licensed']="The user %s has requested access to a licensed survey %s."; +$lang['to_view_request_instructions']="To view the request, login to the NADA site administration and visit the 'Licensed survey requests' page."; +$lang['received_licensed_request']="The %s has received your request for the licensed datafiles. We will notify you via email once your application has been reviewed."; $lang['to_view_request_status']="To view the status of your request, please visit:"; -$lang['for_further_information'] = "For further information, please contact us at"; -$lang['form_not_available'] = "Form has been removed and is no longer available."; -$lang['view_all_requests'] = "View all requests"; -//request status codes -$lang['APPROVED'] = "Approved"; -$lang['DENIED'] = "Denied"; -$lang['PENDING'] = "Pending"; -$lang['MOREINFO'] = "More information is required"; -$lang['CANCELLED'] = "Cancelled"; - -$lang['reason_login_licensed_access'] = "To request access to licensed datasets, please login to the website to continue."; -$lang['forward_lic_request'] = "Forward request"; -$lang['comments_history'] = "Comments history"; -$lang['view_comments_history'] = "View history"; -$lang['comment_by'] = "By"; -$lang['show_hide'] = "Show/Hide"; -$lang['comment'] = "Comment"; -$lang['communicate_history'] = "History"; -$lang['sent_by'] = "Sent by"; -$lang['forward_history'] = "History"; -$lang['data_restricted_use'] = "The data is provided only for the purpose described in the request form, to be able to use the data for any other purpose make a new access request."; -$lang['data_request_for'] = "Data request"; - -$lang['request_history'] = "View request history"; -$lang['study_notes'] = "View study notes"; - -$lang['note_type'] = "Type"; -$lang['note'] = "Note"; -$lang['additional_info'] = "Additional information requested"; -$lang['request_additional_info_submitted'] = "Thank you for updating request. We will notify you via email once your application has been reviewed."; -$lang['email_sent'] = "Your message has been sent!"; -$lang['provide_additonal_info_for_your_request'] = "Please use this box to provide additional information needed to process your data request."; - -$lang['click_on_a_lic_request_to_see_status_or_download_data'] = "Click on a request to view status or download data for approved requests."; -$lang['make_new_lic_request'] = "Make new request"; -$lang['no_microdata_files_found'] = "No microdata files were found!"; - - -$lang['all_requests'] = "All requests"; -$lang['pending'] = "Pending"; -$lang['approved'] = "Approved"; -$lang['denied'] = "Denied"; -$lang['request_more_info'] = "Requested more info"; -$lang['cancelled'] = "Cancelled"; - -$lang['study_data_files'] = "Microdata Files"; -$lang['study_resources'] = "Other Materials"; -$lang['datasets_requested'] = "Dataset(s) requested"; -$lang['request_title'] = "Request title"; -$lang['download_microdata_and_resources'] = "Download Microdata and other related materials"; - - +$lang['for_further_information']="For further information, please contact us at"; +$lang['form_not_available']="Form has been removed and is no longer available."; +$lang['view_all_requests']="View all requests"; +$lang['APPROVED']="Approved"; +$lang['DENIED']="Denied"; +$lang['PENDING']="Pending"; +$lang['MOREINFO']="More information is required"; +$lang['CANCELLED']="Cancelled"; +$lang['reason_login_licensed_access']="To request access to licensed datasets, please login to the website to continue."; +$lang['forward_lic_request']="Forward request"; +$lang['comments_history']="Comments history"; +$lang['view_comments_history']="View history"; +$lang['comment_by']="By"; +$lang['show_hide']="Show/Hide"; +$lang['comment']="Comment"; +$lang['communicate_history']="History"; +$lang['sent_by']="Sent by"; +$lang['forward_history']="History"; +$lang['data_restricted_use']="The data is provided only for the purpose described in the request form, to be able to use the data for any other purpose make a new access request."; +$lang['data_request_for']="Data request"; +$lang['request_history']="View request history"; +$lang['study_notes']="View study notes"; +$lang['note_type']="Type"; +$lang['note']="Note"; +$lang['additional_info']="Additional information requested"; +$lang['request_additional_info_submitted']="Thank you for updating request. We will notify you via email once your application has been reviewed."; +$lang['email_sent']="Your message has been sent!"; +$lang['provide_additonal_info_for_your_request']="Please use this box to provide additional information needed to process your data request."; +$lang['click_on_a_lic_request_to_see_status_or_download_data']="Click on a request to view status or download data for approved requests."; +$lang['make_new_lic_request']="Make new request"; +$lang['no_microdata_files_found']="No microdata files were found!"; +$lang['all_requests']="All requests"; +$lang['pending']="Pending"; +$lang['denied']="Denied"; +$lang['cancelled']="Cancelled"; +$lang['study_data_files']="Microdata Files"; +$lang['study_resources']="Other Materials"; +$lang['datasets_requested']="Dataset(s) requested"; +$lang['request_title']="Request title"; +$lang['download_microdata_and_resources']="Download Microdata and other related materials"; /* End of file licensed_request_lang.php */ -/* Location: ./system/language/english/licensed_request_lang.php */ \ No newline at end of file +/* Location: ./application/language/english/licensed_request_lang.php */ \ No newline at end of file diff --git a/application/language/base/menu_lang.php b/application/language/base/menu_lang.php index b3c929648..5eeea274e 100644 --- a/application/language/base/menu_lang.php +++ b/application/language/base/menu_lang.php @@ -1,44 +1,46 @@ - +
  • You are free to copy, distribute, adapt, display or include the data in other products for commercial and noncommercial purposes at no cost subject to certain limitations summarized below. +
  • You must include attribution for the data you use in the manner indicated in the metadata included with the data. +
  • You must not claim or imply that The World Bank endorses your use of the data by or use The World Bank's logo(s) or trademark(s) in conjunction with such use. +
  • Other parties may have ownership interests in some of the materials contained on The World Bank Web site. For example, +we maintain a list of some specific data within the Datasets that you may not redistribute or reuse without first contacting the original content provider, +as well as information regarding how to contact the original content provider. Before incorporating any data in other products, please check the list: Terms of use: Restricted Data +
  • The World Bank makes no warranties with respect to the data and you agree The World Bank shall not be liable to you in connection with your use of the data. + +

    This is only a summary of the Terms of Use for Datasets Listed in The World Bank Data Catalogue. Please read the actual agreement that controls your use of the Datasets, +which is available here: Terms of use for datasets. Also see +World Bank Terms and Conditions.

    "; + + +/* End of file open_data_lang.php */ +/* Location: ./application/language/english/open_data_lang.php */ \ No newline at end of file diff --git a/application/language/base/permissions_lang.php b/application/language/base/permissions_lang.php index bb919e7f7..a75dd4412 100644 --- a/application/language/base/permissions_lang.php +++ b/application/language/base/permissions_lang.php @@ -1,22 +1,22 @@ -
  • The data and other materials provided by the National Data Archive will not be redistributed or sold to other individuals, institutions, or organizations @@ -44,12 +41,12 @@ Archive will conform to widely-accepted standards of practice and legal restrictions that are intended to protect the confidentiality of respondents.

    "; +$lang['public_use_files']="Public Use Files"; +$lang['surveys_in_collection']="The collection [%s] contains the following surveys:"; +$lang['collection_data_files']="Public Use Files by Collection"; +$lang['collection_requested']="Collection access requested"; +$lang['public_use_data_access_by_collection_message']="You have been granted access to all public use studies in the collection. Please visit each study page to download the data files and other documentation."; +$lang['public_use_data_access_by_collection']="Download data files"; -$lang['public_use_files'] = "Public Use Files"; -$lang['surveys_in_collection']='The collection [%s] contains the following surveys:'; -$lang['collection_data_files']='Public Use Files by Collection'; -$lang['collection_requested']='Collection access requested'; -$lang['public_use_data_access_by_collection_message']='You have been granted access to all public use studies in the collection. Please visit each study page to download the data files and other documentation.'; -$lang['public_use_data_access_by_collection']='Download data files'; /* End of file public_access_terms_lang.php */ -/* Location: ./system/language/english/public_access_terms_lang.php */ \ No newline at end of file +/* Location: ./application/language/english/public_access_terms_lang.php */ \ No newline at end of file diff --git a/application/language/base/public_request_lang.php b/application/language/base/public_request_lang.php index 374d5ee35..beebec561 100644 --- a/application/language/base/public_request_lang.php +++ b/application/language/base/public_request_lang.php @@ -1,20 +1,17 @@ - + - Operator - Meaning + Operator + Meaning space @@ -30,7 +31,7 @@ prepended (put at beginning). - "" + "" Double quotes at the beginning and end of a phrase, matches only rows that contain the complete phrase, as it was typed. @@ -64,11 +65,11 @@ Employed, but exclude results for Kenya from the results.

  • -
  • Placing quotation marks "" around a search term +
  • Placing quotation marks "" around a search term will force the term to be evaluated as one term. For example: to limit a search to study descriptions that contain the exact sequence of words -health study in them one would type "Health -Study" between quotation marks. Without the +health study in them one would type "Health +Study" between quotation marks. Without the quotation marks the search would show all studies with health or study in them. With the quotation marks only studies with the exact wording in the sequence health study will be shown.
    @@ -85,8 +86,7 @@
  • -'; - +"; /* End of file search_help_lang.php */ -/* Location: ./system/language/english/search_help_lang.php */ \ No newline at end of file +/* Location: ./application/language/english/search_help_lang.php */ \ No newline at end of file diff --git a/application/language/base/site_menu_lang.php b/application/language/base/site_menu_lang.php index 8d2347294..82c7e793e 100644 --- a/application/language/base/site_menu_lang.php +++ b/application/language/base/site_menu_lang.php @@ -1,30 +1,27 @@ -%s website. To complete your registration and activate your user account, please visit the following URL:"; -$lang['your_account_details'] = "You account details are"; -$lang['do_not_reply_to_this_email'] = "DO NOT REPLY TO THIS EMAIL"; - -$lang['click_url_to_reset_password'] = "To reset your password, click on the link below or open the url in a web browser"; -$lang['request_password_ignore'] = "If you did not request password reset, ignore this message."; - -$lang['enter_email_to_reset_password'] = "Please enter your email address so we can send you an email to reset your password."; -$lang['password_is_sent'] = "Your password has been reset and a new password is sent to your email address."; -$lang['login_with_new_password'] = "Click here to login with your new password."; -$lang['message_sent_to_your_email'] = "An email message has been sent to your email address, please check your inbox."; - -$lang['password_reset_to'] = "You password has been reset to %s. To login to the website, your account details are:"; -$lang['forgot_password_verification'] = "Forgotten Password Verification"; -$lang['account_activation'] = "Account activation"; -$lang['callback_country_invalid'] = "The Country field is required."; -$lang['log_in'] = "Log in"; -$lang['site_login_privacy_terms'] = "Information you provide by registering or login to our catalog will be used in compliance with the terms of the NSO's Privacy Policy."; -$lang['impersonate_user'] = "Impersonate as another user"; -$lang['impersonate_msg'] = "Select the account below to impersonate as"; - -$lang['general_user_accounts'] = "General user accounts (no admin access)"; -$lang['general_user_accounts_description'] = "General site users with no access to site administration"; - -$lang['edit_user_permissions'] = "Edit user permissions"; - -$lang['site_admin_accounts'] = "Site administrators (full access)"; -$lang['site_admin_accounts_description'] = "Full control over all site sections"; - -$lang['site_admin_limited_accounts'] = "Site administrators (limited access)"; -$lang['site_admin_limited_accounts_description'] = "Limit user access to the site administration and control permissions per collection for the user"; - -$lang['user_site_level_permissions'] = "Site level permissions"; - -$lang['assigned_user_groups'] = "Global user roles"; -$lang['manage_permissions'] = "Manage permissions"; -$lang['permissions_per_collection'] = "Permissions per collection"; - +%s website. To complete your registration and activate your user account, please visit the following URL:"; +$lang['your_account_details']="You account details are"; +$lang['do_not_reply_to_this_email']="DO NOT REPLY TO THIS EMAIL"; +$lang['click_url_to_reset_password']="To reset your password, click on the link below or open the url in a web browser"; +$lang['request_password_ignore']="If you did not request password reset, ignore this message."; +$lang['enter_email_to_reset_password']="Please enter your email address so we can send you an email to reset your password."; +$lang['password_is_sent']="Your password has been reset and a new password is sent to your email address."; +$lang['login_with_new_password']="Click here to login with your new password."; +$lang['message_sent_to_your_email']="An email message has been sent to your email address, please check your inbox."; +$lang['password_reset_to']="You password has been reset to %s. To login to the website, your account details are:"; +$lang['forgot_password_verification']="Forgotten Password Verification"; +$lang['account_activation']="Account activation"; +$lang['callback_country_invalid']="The Country field is required."; +$lang['log_in']="Log in"; +$lang['site_login_privacy_terms']="Information you provide by registering or login to our catalog will be used in compliance with the terms of the NSO's Privacy Policy."; +$lang['impersonate_user']="Impersonate as another user"; +$lang['impersonate_msg']="Select the account below to impersonate as"; +$lang['general_user_accounts']="General user accounts (no admin access)"; +$lang['general_user_accounts_description']="General site users with no access to site administration"; +$lang['edit_user_permissions']="Edit user permissions"; +$lang['site_admin_accounts']="Site administrators (full access)"; +$lang['site_admin_accounts_description']="Full control over all site sections"; +$lang['site_admin_limited_accounts']="Site administrators (limited access)"; +$lang['site_admin_limited_accounts_description']="Limit user access to the site administration and control permissions per collection for the user"; +$lang['user_site_level_permissions']="Site level permissions"; +$lang['assigned_user_groups']="Global user roles"; +$lang['manage_permissions']="Manage permissions"; +$lang['permissions_per_collection']="Permissions per collection"; /* End of file users_lang.php */ -/* Location: ./system/language/english/users_lang.php */ \ No newline at end of file +/* Location: ./application/language/english/users_lang.php */ \ No newline at end of file diff --git a/application/language/base/vocabularies_lang.php b/application/language/base/vocabularies_lang.php index 7f3bca0db..e6312eea0 100644 --- a/application/language/base/vocabularies_lang.php +++ b/application/language/base/vocabularies_lang.php @@ -1,17 +1,16 @@ -CI->recaptcha->recaptcha_check_answer($this->CI->input->server('REMOTE_ADDR'), - $this->CI->input->post('recaptcha_challenge_field'), - $this->CI->input->post('recaptcha_response_field'), - array(), - false - ); + $response = $this->CI->recaptcha->recaptcha_check_answer( + $this->CI->input->server('REMOTE_ADDR'), + $this->CI->input->post($this->get_question_field()), + $debug=false + ); return $response['is_valid']; } public function get_question_field() { - return 'recaptcha_response_field'; + return 'g-recaptcha-response'; } } diff --git a/application/libraries/DDI2_import.php b/application/libraries/DDI2_import.php index f933abdc4..caa7206ad 100644 --- a/application/libraries/DDI2_import.php +++ b/application/libraries/DDI2_import.php @@ -105,15 +105,11 @@ public function import($params,$sid=null) if(!$this->overwrite){ throw new Exception("SURVEY_ALREADY_EXISTS: ".$sid); } - - //check if study is owned by the active repository - $owner_repository=$this->ci->Catalog_model->get_study_owner($sid); - if (!$owner_repository){ - $owner_repository='central'; - } - - $this->repositoryid=$owner_repository; + //load existing options + $dataset_row=$this->ci->dataset_manager->get_row($sid); + $this->repositoryid=$dataset_row['repositoryid']; + $this->formid=$dataset_row['formid']; } $repositoryid=$this->repositoryid; @@ -459,6 +455,9 @@ function sanitize_filename($name) private function import_variables($sid,$data_files, $variable_iterator) { + //delete existing variables + variables metadata + $this->ci->Variable_model->remove_all_variables($sid); + if(!$data_files){ return 0; } @@ -467,9 +466,6 @@ private function import_variables($sid,$data_files, $variable_iterator) return 0; } - //delete existing variables + variables metadata - $this->ci->Variable_model->remove_all_variables($sid); - $batch_inserts=true; //enable or disable batch inserts $batch_insert_size=200; //rows inserted at once $batch_insert_count=0; diff --git a/application/libraries/DDI_Utils.php b/application/libraries/DDI_Utils.php new file mode 100644 index 000000000..a33f053ea --- /dev/null +++ b/application/libraries/DDI_Utils.php @@ -0,0 +1,253 @@ +ci =& get_instance(); + $this->ci->load->model("Catalog_model"); + } + + + + /** + * + * Strip metadata elements from the DDI + * + * @strip - 'summary_stats', 'variables', 'keep_basic' + * + **/ + function strip_ddi($sid, $strip, $keep_original) + { + switch($strip){ + case 'summary_stats': + return $this->strip_ddi_summary_stats($sid,$keep_original); + break; + + case 'variables': + return $this->strip_ddi_variables($sid,$keep_original); + break; + + case 'keep_basic': + return $this->strip_ddi_to_basic($sid,$keep_original); + break; + } + + return false; + } + + /** + * + * + * Strip summary stats from DDI + * + */ + function strip_ddi_summary_stats($sid, $keep_original=true) + { + $xpath_array=array( + '//ddi:codeBook/ddi:dataDscr//ddi:sumStat'=>'sumStat' + ); + + return $this->strip_ddi_parts($sid,$xpath_array, $keep_original); + } + + + + /** + * + * + * Strip data files and variables from DDI + * + */ + function strip_ddi_variables($sid, $keep_original=true) + { + $xpath_array=array( + '//ddi:codeBook/ddi:dataDscr'=>'dataDscr', + '//ddi:codeBook/ddi:fileDscr'=>'fileDscr', + ); + + return $this->strip_ddi_parts($sid,$xpath_array, $keep_original); + } + + + + /** + * + * + * Strip all elements except titlStmt + * + */ + function strip_ddi_to_basic($sid, $keep_original=true) + { + //paths to trim + $xpath_array=array( + '//ddi:codeBook/ddi:docDscr'=>'docDscr', + //'//ddi:codeBook/ddi:stdyDscr'=>'stdyDscr', + '//ddi:codeBook/ddi:stdyDscr//ddi:producer'=>'producer', + '//ddi:codeBook/ddi:stdyDscr//ddi:fundAg'=>'sponsor', + '//ddi:codeBook/ddi:stdyDscr//ddi:serStmt'=>'sername', + '//ddi:codeBook/ddi:stdyDscr//ddi:geogCover'=>'geogCover', + '//ddi:codeBook/ddi:stdyDscr//ddi:universe'=>'universe', + '//ddi:codeBook/ddi:stdyDscr//ddi:method'=>'method', + '//ddi:codeBook/ddi:stdyDscr//ddi:dataAccs'=>'dataAccs', + '//ddi:codeBook/ddi:stdyDscr//ddi:distStmt'=>'distStmt', + + '//ddi:codeBook/ddi:stdyDscr//ddi:verStmt'=>'verStmt', + '//ddi:codeBook/ddi:stdyDscr//ddi:subject'=>'subject', + + '//ddi:codeBook/ddi:stdyDscr/ddi:stdyInfo/ddi:abstract'=>'abstract', + '//ddi:codeBook/ddi:stdyDscr/ddi:stdyInfo/ddi:sumDscr/ddi:timePrd'=>'timePrd', + '//ddi:codeBook/ddi:stdyDscr/ddi:stdyInfo/ddi:sumDscr/ddi:geogCover'=>'geogCover', + '//ddi:codeBook/ddi:stdyDscr/ddi:stdyInfo/ddi:sumDscr/ddi:anlyUnit'=>'anlyUnit', + '//ddi:codeBook/ddi:stdyDscr/ddi:stdyInfo/ddi:sumDscr/ddi:universe'=>'universe', + '//ddi:codeBook/ddi:stdyDscr/ddi:stdyInfo/ddi:sumDscr/ddi:dataKind'=>'dataKind', + '//ddi:codeBook/ddi:stdyDscr/ddi:stdyInfo/ddi:notes'=>'notes', + '//ddi:codeBook/ddi:stdyDscr/ddi:method/ddi:dataColl/ddi:dataCollector'=>'dataCollector', + '//ddi:codeBook/ddi:stdyDscr/ddi:method/ddi:dataColl/ddi:sampProc'=>'sampProc', + '//ddi:codeBook/ddi:stdyDscr/ddi:method/ddi:dataColl/ddi:deviat'=>'deviat', + '//ddi:codeBook/ddi:stdyDscr/ddi:method/ddi:dataColl/ddi:collMode'=>'collMode', + '//ddi:codeBook/ddi:stdyDscr/ddi:method/ddi:dataColl/ddi:resInstru'=>'resInstru', + '//ddi:codeBook/ddi:stdyDscr/ddi:method/ddi:dataColl/ddi:collSitu'=>'collSitu', + '//ddi:codeBook/ddi:stdyDscr/ddi:method/ddi:dataColl/ddi:actMin'=>'actMin', + '//ddi:codeBook/ddi:stdyDscr/ddi:method/ddi:dataColl/ddi:weight'=>'weight', + '//ddi:codeBook/ddi:stdyDscr/ddi:method/ddi:dataColl/ddi:cleanOps'=>'cleanOps', + '//ddi:codeBook/ddi:stdyDscr/ddi:method/ddi:notes'=>'notes', + '//ddi:codeBook/ddi:stdyDscr/ddi:method/ddi:anlyInfo/ddi:respRate'=>'respRate', + '//ddi:codeBook/ddi:stdyDscr/ddi:method/ddi:anlyInfo/ddi:EstSmpErr'=>'EstSmpErr', + '//ddi:codeBook/ddi:stdyDscr/ddi:method/ddi:anlyInfo/ddi:dataAppr'=>'dataAppr', + '//ddi:codeBook/ddi:stdyDscr/ddi:dataAccs/ddi:useStmt/ddi:confDec'=>'confDec', + '//ddi:codeBook/ddi:stdyDscr/ddi:dataAccs/ddi:useStmt/ddi:contact'=>'contact', + '//ddi:codeBook/ddi:stdyDscr/ddi:dataAccs/ddi:useStmt/ddi:citReq'=>'citReq', + '//ddi:codeBook/ddi:stdyDscr/ddi:dataAccs/ddi:useStmt/ddi:conditions'=>'conditions', + '//ddi:codeBook/ddi:stdyDscr/ddi:dataAccs/ddi:useStmt/ddi:disclaimer'=>'disclaimer', + '//ddi:codeBook/ddi:stdyDscr/ddi:citation/ddi:prodStmt/ddi:copyright'=>'copyright', + '//ddi:codeBook/ddi:stdyDscr/ddi:citation/ddi:prodStmt/ddi:fundAg'=>'fundAg', + '//ddi:codeBook/ddi:stdyDscr/ddi:citation/ddi:distStmt/ddi:contact'=>'contact', + + '//ddi:codeBook/ddi:dataDscr'=>'dataDscr', + '//ddi:codeBook/ddi:fileDscr'=>'fileDscr', + '//ddi:codeBook/ddi:dataDscr//ddi:sumStat'=>'sumStat', + '//ddi:codeBook/ddi:otherMat'=>'otherMat', + ); + + return $this->strip_ddi_parts($sid,$xpath_array, $keep_original); + } + + + /** + * + * Strip elements from the DDI codebook + * + * @sid - Survey ID + * @xpath_array - array of xpaths to be removed + * @keep_original - make a copy of the original file? + * + * + */ + function strip_ddi_parts($sid, $xpath_array=array(),$keep_original=true) + { + $ddi_file=$this->ci->Catalog_model->get_survey_ddi_path($sid); + + if (!file_exists($ddi_file)){ + throw new Exception("FILE_NOT_FOUND: ". $ddi_file); + } + + if(!is_array($xpath_array) || !count($xpath_array)>0){ + throw new Exception ("PARAM:XPATH_ARRAY_IS_EMPTY"); + } + + $doc = new DOMDocument; + $doc->load($ddi_file); + + $xpath=new DOMXPath($doc); + $rootNamespace = $doc->lookupNamespaceUri($doc->namespaceURI); + $xpath->registerNamespace('ddi', $rootNamespace); + + foreach($xpath_array as $xpath_key=>$value) + { + //find all matching nodes + $nodes = $xpath->query($xpath_key); + + //replace all matching nodes + foreach($nodes as $node) { + //$result->parentNode->removeChild($result); + $replacement_element=$doc->createElement($value); + $node->parentNode->replaceChild($replacement_element, $node); + } + } + + //make a copy of the original file + if ($keep_original==true){ + $original_file=str_replace(".xml","-original.xml",$ddi_file); + //skip if backup file already exists + if(!file_exists($original_file)){ + copy($ddi_file,$original_file); + }; + } + + file_put_contents($ddi_file,$doc->saveXML()); + return $ddi_file; + } + + + + /** + * + * Reload metadata from DDI + * + * Updates database with the metadata from DDI + * + * partial - if yes, only update study level metadata + * + **/ + function reload_ddi($id=NULL,$user_id=null, $partial=false) + { + $this->ci->load->model("Catalog_model"); + $this->ci->load->library('DDI2_import'); + $this->ci->load->library('Dataset_manager'); + + //get survey ddi file path by id + $ddi_file=$this->ci->Catalog_model->get_survey_ddi_path($id); + + if ($ddi_file===FALSE){ + throw new Exception("DDI_FILE_NOT_FOUND: ".$ddi_file); + } + + $dataset=$this->ci->dataset_manager->get_row($id); + + $params=array( + 'file_type'=>'survey', + 'file_path'=>$ddi_file, + 'repositoryid'=>$dataset['repositoryid'], + 'overwrite'=>'yes', + 'user_id'=>$user_id, + 'partial'=>$partial + ); + + $result=$this->ci->ddi2_import->import($params,$id); + + //reset changed and created dates + $update_options=array( + 'changed'=>$dataset['changed'], + 'created'=>$dataset['created'], + 'repositoryid'=>$dataset['repositoryid'], + //'link_da'=>$dataset['link_da'], + 'formid'=>$dataset['formid'] + ); + + $this->ci->dataset_manager->update_options($id,$update_options); + + //get updated info + $dataset=$this->ci->dataset_manager->get_row($id); + + return $dataset; + } + +} \ No newline at end of file diff --git a/application/libraries/Metadata_parser/classes/DDI2Reader.php b/application/libraries/Metadata_parser/classes/DDI2Reader.php index eef4dc5b9..4b54b8b34 100644 --- a/application/libraries/Metadata_parser/classes/DDI2Reader.php +++ b/application/libraries/Metadata_parser/classes/DDI2Reader.php @@ -351,8 +351,9 @@ function __construct($xml_file) 'label' => 'Keyword', 'type' => 'table', 'cols' => array( - '.' => 'keyword', - '@uri' => 'uri', + '.' => 'keyword', + '@vocab'=>'vocab', + '@uri' => 'uri' ) ); diff --git a/application/libraries/Nada_csrf.php b/application/libraries/Nada_csrf.php new file mode 100644 index 000000000..dcb14bb84 --- /dev/null +++ b/application/libraries/Nada_csrf.php @@ -0,0 +1,75 @@ +slimGuard = new \Slim\Csrf\Guard; + $this->slimGuard->validateStorage(); + $this->ci =& get_instance(); + } + + function generate_token() + { + $this->slimGuard->generateToken(); + + $this->token_name_key = $this->slimGuard->getTokenNameKey(); + $this->token_value_key = $this->slimGuard->getTokenValueKey(); + $this->token_name = $this->slimGuard->getTokenName(); + $this->token_value = $this->slimGuard->getTokenValue(); + + return [ + 'keys' => [ + 'name' => $this->token_name_key, + 'value' => $this->token_value_key + ], + 'name' => $this->token_name, + 'value' => $this->token_value + ]; + + } + + + function get_token_name() + { + return $this->token_name; + } + + function get_token_name_key() + { + return $this->token_name_key; + } + + function get_token_value_key() + { + return $this->token_value_key; + } + + function get_token_value() + { + return $this->token_value; + } + + + function validate_token() + { + return $this->slimGuard->validateToken($this->ci->input->post($this->token_name_key), $this->ci->input->post($this->token_value_key)); + } + + +} \ No newline at end of file diff --git a/application/libraries/Recaptcha.php b/application/libraries/Recaptcha.php index 6c34b91e1..162cb7b38 100644 --- a/application/libraries/Recaptcha.php +++ b/application/libraries/Recaptcha.php @@ -1,241 +1,73 @@ config->load("captcha");//load captcha configurations + $CI->config->load("captcha");//load captcha configurations $this->recaptcha=config_item('recaptcha'); } - /** - * Gets the challenge HTML (javascript and non-javascript version). - * This is called from the browser, and the resulting reCAPTCHA HTML widget - * is embedded within the HTML form it was called from. - * @param string $pubkey A public key for reCAPTCHA - * @param string $error The error given by reCAPTCHA (optional, default is null) - * @param boolean $use_ssl Should the request be made over ssl? (optional, default is false) - * @return string - The HTML to be embedded in the user's form. + /** + * + * Returns HTML/JS for embedding on the form + * */ - function recaptcha_get_html ($error = null, $use_ssl = false) + function recaptcha_get_html () { - if ($this->recaptcha['publickey'] == null || $this->recaptcha['publickey'] == '') { - die ("To use reCAPTCHA you must get an API key from https://www.google.com/recaptcha/admin/create"); - } - - if ($use_ssl) { - $server = $this->recaptcha['apisecureserver']; - } else { - $server = $this->recaptcha['apiserver']; - } - - $errorpart = ""; - if ($error) { - $errorpart = "&error=" . $error; - } - return ' - - - '; + if ($this->recaptcha['publickey'] == null || $this->recaptcha['publickey'] == '') { + die ("To use reCAPTCHA you must get an API key from https://www.google.com/recaptcha/admin/create"); + } + + return ' +
    + '; } /** - * Calls an HTTP POST function to verify if the user's guess was correct - * @param string $privkey - * @param string $remoteip - * @param string $challenge - * @param string $response - * @param array $extra_params an array of extra variables to post to the server - * @param boolean $debug if true this var, always return ReCaptchaResponse['is_valid']=true - * @return ReCaptchaResponse - */ - function recaptcha_check_answer ($remoteip, $challenge, $response, $extra_params = array(),$debug=false) + * + * validate Recaptcha on form submission + * + * @recaptcha_response = value of g-captcha-response + */ + function recaptcha_check_answer ($remoteip, $recaptcha_response) { - if ($this->recaptcha['privatekey'] == null || $this->recaptcha['privatekey'] == '') { - die ("To use reCAPTCHA you must get an API key from https://www.google.com/recaptcha/admin/create"); - } - if ($remoteip == null || $remoteip == '') { - die ("For security reasons, you must pass the remote ip to reCAPTCHA"); - } + // If the form submission includes the "g-captcha-response" field + // Create an instance of the service using your secret + $recaptcha = new \ReCaptcha\ReCaptcha($this->recaptcha['privatekey']); - //discard spam submissions - if ($challenge == null || strlen($challenge) == 0 || $response == null || strlen($response) == 0) { - $recaptcha_response = array( - 'is_valid'=>false, - 'error'=>'incorrect-captcha-sol' - ); - return $recaptcha_response; - } + // If file_get_contents() is locked down on your PHP installation to disallow + // its use with URLs, then you can use the alternative request method instead. + // This makes use of fsockopen() instead. + // $recaptcha = new \ReCaptcha\ReCaptcha($secret, new \ReCaptcha\RequestMethod\SocketPost()); - $response = self::_recaptcha_http_post ($this->recaptcha['verifyserver'], "/recaptcha/api/verify", - array ( - 'privatekey' => $this->recaptcha['privatekey'], - 'remoteip' => $remoteip, - 'challenge' => $challenge, - 'response' => $response - ) + $extra_params - ); + // Make the call to verify the response and also pass the user's IP address + $resp = $recaptcha->verify($recaptcha_response, $remoteip); - $answers = explode ("\n", $response [1]); - $recaptcha_response = array(); - - if (trim ($answers [0]) == 'true') { - $recaptcha_response['is_valid'] = true; - } - else { - $recaptcha_response['is_valid'] = false; - $recaptcha_response['error'] = $answers [1]; - } - if($debug===TRUE){ + $recaptcha_response = array(); + + if ($resp->isSuccess()){ $recaptcha_response['is_valid'] = true; - } - return $recaptcha_response; - + } + else { + $recaptcha_response['is_valid'] = false; + $recaptcha_response['error'] = $resp->getErrorCodes(); + } + + return $recaptcha_response; } - /** - * Submits an HTTP POST to a reCAPTCHA server - * @param string $host - * @param string $path - * @param array $data - * @param int port - * @return array response - */ - function _recaptcha_http_post($host, $path, $data, $port = 80) { - - $req = self::_recaptcha_qsencode ($data); - $http_request = "POST $path HTTP/1.0\r\n"; - $http_request .= "Host: $host\r\n"; - $http_request .= "Content-Type: application/x-www-form-urlencoded;\r\n"; - $http_request .= "Content-Length: " . strlen($req) . "\r\n"; - $http_request .= "User-Agent: reCAPTCHA/PHP\r\n"; - $http_request .= "\r\n"; - $http_request .= $req; - - $response = ''; - if( false == ( $fs = @fsockopen($host, $port, $errno, $errstr, 10) ) ) { - die ('Could not open socket'); - } - - fwrite($fs, $http_request); - - while ( !feof($fs) ) - $response .= fgets($fs, 1160); // One TCP-IP packet - fclose($fs); - $response = explode("\r\n\r\n", $response, 2); - - return $response; - } - /** - * Encodes the given data into a query string format - * @param $data - array of string elements to be encoded - * @return string - encoded request - */ - function _recaptcha_qsencode ($data) { - $req = ""; - foreach ( $data as $key => $value ) - $req .= $key . '=' . urlencode( stripslashes($value) ) . '&'; - - // Cut the last '&' - $req=substr($req,0,strlen($req)-1); - return $req; - } - - /** - * gets a URL where the user can sign up for reCAPTCHA. If your application - * has a configuration page where you enter a key, you should provide a link - * using this function. - * @param string $domain The domain where the page is hosted - * @param string $appname The name of your application - */ - function recaptcha_get_signup_url ($domain = null, $appname = null) { - return "https://www.google.com/recaptcha/admin/create?" . self::_recaptcha_qsencode (array ('domains' => $domain, 'app' => $appname)); - } - - function _recaptcha_aes_pad($val) { - $block_size = 16; - $numpad = $block_size - (strlen ($val) % $block_size); - return str_pad($val, strlen ($val) + $numpad, chr($numpad)); - } - /* Mailhide related code */ - - function _recaptcha_aes_encrypt($val,$ky) { - if (! function_exists ("mcrypt_encrypt")) { - die ("To use reCAPTCHA Mailhide, you need to have the mcrypt php module installed."); - } - $mode=MCRYPT_MODE_CBC; - $enc=MCRYPT_RIJNDAEL_128; - $val=self::_recaptcha_aes_pad($val); - return mcrypt_encrypt($enc, $ky, $val, $mode, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"); - } - - - function _recaptcha_mailhide_urlbase64 ($x) { - return strtr(base64_encode ($x), '+/', '-_'); - } - /* gets the reCAPTCHA Mailhide url for a given email, public key and private key */ - function recaptcha_mailhide_url($email) { - if ($this->recaptcha['mailhide']['publickey'] == '' || $this->recaptcha['mailhide']['publickey'] == null || $this->recaptcha['mailhide']['privatekey'] == "" || $this->recaptcha['mailhide']['privatekey'] == null) { - die ("To use reCAPTCHA Mailhide, you have to sign up for a public and private key, " . - "you can do so at http://www.google.com/recaptcha/mailhide/apikey"); - } - - - $ky = pack('H*', $this->recaptcha['mailhide']['privatekey']); - $cryptmail = self::_recaptcha_aes_encrypt ($email, $ky); - - return "http://www.google.com/recaptcha/mailhide/d?k=" . $this->recaptcha['mailhide']['publickey'] . "&c=" . self::_recaptcha_mailhide_urlbase64 ($cryptmail); - } - - /** - * gets the parts of the email to expose to the user. - * eg, given johndoe@example,com return ["john", "example.com"]. - * the email is then displayed as john...@example.com - */ - function _recaptcha_mailhide_email_parts ($email) { - $arr = preg_split("/@/", $email ); - - if (strlen ($arr[0]) <= 4) { - $arr[0] = substr ($arr[0], 0, 1); - } else if (strlen ($arr[0]) <= 6) { - $arr[0] = substr ($arr[0], 0, 3); - } else { - $arr[0] = substr ($arr[0], 0, 4); - } - return $arr; - } - - /** - * Gets html to display an email address given a public an private key. - * to get a key, go to: - * - * http://www.google.com/recaptcha/mailhide/apikey - */ - function recaptcha_mailhide_html($email) { - $emailparts = self::_recaptcha_mailhide_email_parts ($email); - $url = self::recaptcha_mailhide_url ($this->recaptcha['mailhide']['publickey'], $this->recaptcha['mailhide']['privatekey'], $email); - - return htmlentities($emailparts[0]) . "...@" . htmlentities ($emailparts [1]); - - } } \ No newline at end of file diff --git a/application/models/Dataset_image_model.php b/application/models/Dataset_image_model.php index 24559442f..69a0f6d32 100644 --- a/application/models/Dataset_image_model.php +++ b/application/models/Dataset_image_model.php @@ -88,17 +88,14 @@ function create_dataset($type,$options) function get_core_fields($options) { $output=array(); - $output['title']=$this->get_array_nested_value($options,'image_description/photoVideoMetadataIPTC/headline'); - $output['idno']=$this->get_array_nested_value($options,'image_description/photoVideoMetadataIPTC/digitalImageGuid'); - - //todo - $output['nation']=''; - - $output['abbreviation']=$this->get_array_nested_value($options,'table_description/title_statement/alternate_title'); - $creators=(array)$this->get_array_nested_value($options,'image_description/photoVideoMetadataIPTC/creatorNames'); + $output['title']=$this->get_array_nested_value($options,'image_description/iptc/photoVideoMetadataIPTC/headline'); + $output['idno']=$this->get_array_nested_value($options,'image_description/iptc/photoVideoMetadataIPTC/digitalImageGuid'); + $output['nation']=$this->get_array_nested_value($options,'image_description/iptc/photoVideoMetadataIPTC/countryName'); + $output['abbreviation']=''; + $creators=(array)$this->get_array_nested_value($options,'image_description/iptc/photoVideoMetadataIPTC/creatorNames'); $output['authoring_entity']=implode(",", $creators); - $date=explode("-",$this->get_array_nested_value($options,'image_description/photoVideoMetadataIPTC/dateCreated')); + $date=explode("-",$this->get_array_nested_value($options,'image_description/iptc/photoVideoMetadataIPTC/dateCreated')); if(is_array($date)){ $output['year_start']=(int)$date[0]; diff --git a/application/models/Public_model.php b/application/models/Public_model.php index 748f51a7d..06c7ad330 100644 --- a/application/models/Public_model.php +++ b/application/models/Public_model.php @@ -13,7 +13,7 @@ public function __construct() */ function select_single($request_id) { - $this->db->select('p.*,s.titl,s.surveyid,s.proddate, s.nation, u.username,u.email,m.first_name, m.last_name,m.company, m.phone,m.country',FALSE); + $this->db->select('p.*,s.title,s.idno,s.year_start, s.nation, u.username,u.email,m.first_name, m.last_name,m.company, m.phone,m.country',FALSE); $this->db->join('surveys s', 's.id = p.surveyid'); $this->db->join('users u', 'u.id = p.userid','left'); $this->db->join('meta m', 'u.id = m.user_id','left'); @@ -38,7 +38,7 @@ function select_single($request_id) **/ function get_all_public_use_surveys() { - $this->db->select('s.id,s.titl,s.nation,s.year_start,s.year_end'); + $this->db->select('s.id,s.title,s.nation,s.year_start,s.year_end'); $this->db->join('forms', 's.formid = forms.formid','left'); $this->db->where('forms.model','public'); return $this->db->get('surveys s')->result_array(); @@ -50,7 +50,7 @@ function get_all_public_use_surveys() **/ function get_surveys_by_collection($repositoryid) { - $this->db->select('s.id,s.titl,s.nation,s.year_start,s.year_end,forms.model'); + $this->db->select('s.id,s.title,s.nation,s.year_start,s.year_end,forms.model'); $this->db->from('surveys s'); $this->db->join('survey_repos repos', 's.id = repos.sid','left'); $this->db->join('forms', 'forms.formid = s.formid','inner'); diff --git a/application/models/Reports_model.php b/application/models/Reports_model.php index 73af19323..4f9d2bc67 100644 --- a/application/models/Reports_model.php +++ b/application/models/Reports_model.php @@ -34,8 +34,8 @@ function get_survey_summary($start, $end) { $sql='SELECT s.id as id, - s.surveyid as surveyid, - s.titl as titl, + s.idno as idno, + s.title as title, count(*) as visits FROM sitelogs n inner join surveys s on n. surveyid=s.id @@ -46,7 +46,7 @@ function get_survey_summary($start, $end) $sql.=' and (logtime between '.$start.' and '.$end.')'; } - $sql.=' group by s.surveyid, s.titl, s.id'; + $sql.=' group by s.idno, s.title, s.id'; $sql.= ' order by visits desc'; $query=$this->db->query($sql)->result_array(); @@ -58,11 +58,11 @@ function get_survey_detailed_all($start,$end) { $sql='SELECT s.id as id, - s.surveyid as survey, - s.titl as title, + s.idno, + s.title as title, n.section as section, s.nation as country, - s.proddate as year, + s.year_start as year, count(*) as visits FROM sitelogs n inner join surveys s on n. surveyid=s.id @@ -72,7 +72,7 @@ function get_survey_detailed_all($start,$end) { $sql.=' and (logtime between '.$start.' and '.$end.')'; } - $sql.=' group by s.surveyid, s.id, s.titl, n.section'; + $sql.=' group by s.idno, s.id, s.title, n.section'; return $this->db->query($sql)->result_array(); } @@ -88,11 +88,11 @@ function get_survey_detailed($start,$end) { $sql='SELECT s.id as id, - s.surveyid as survey, - s.titl as title, + s.idno as idno, + s.title as title, n.section as section, s.nation as country, - s.proddate as year, + s.year_start as year, count(*) as visits FROM sitelogs n inner join surveys s on n. surveyid=s.id @@ -105,7 +105,7 @@ function get_survey_detailed($start,$end) } - $sql.=' group by s.surveyid, s.id, s.titl, n.section'; + $sql.=' group by s.idno, s.id, s.title, n.section'; $rows=$this->db->query($sql)->result_array(); $result[]=$rows; @@ -121,31 +121,7 @@ function get_survey_detailed($start,$end) **/ function downloads_detailed($start=NULL,$end=NULL) { - /* - #downloads detailed report - select - sitelogs.id, - logtime, - ip, - sitelogs.surveyid, - users.username, - users.email, - meta.company, - meta.country, - keyword as downloadid, - surveys.titl as survey_title, - resources.title as download_title, - resources.filename as download_filename - - from sitelogs - inner join surveys on surveys.id =sitelogs.surveyid - inner join resources on resources.resource_id=sitelogs.keyword - left join users on users.email = sitelogs.username - left join meta on users.id=meta.id - - where sitelogs.section like '%download%'; - */ - + $sql='select sitelogs.id, logtime, @@ -156,7 +132,7 @@ function downloads_detailed($start=NULL,$end=NULL) meta.company, meta.country, keyword as downloadid, - surveys.titl as survey_title, + surveys.title as survey_title, resources.title as download_title, resources.filename as download_filename, forms.model as form_type @@ -236,7 +212,7 @@ function public_requests($start=NULL,$end=NULL) { $sql='select p.*, - s.titl as survey_title, + s.title as survey_title, u.username, u.email, meta.company, @@ -311,7 +287,7 @@ function survey_summary_statistics() { $sql='select s.id, - titl, + title, varcount, dirpath, s.formid, diff --git a/application/models/Repository_model.php b/application/models/Repository_model.php index 27beded51..3e16f3926 100644 --- a/application/models/Repository_model.php +++ b/application/models/Repository_model.php @@ -352,10 +352,10 @@ function get_repositories($published=FALSE, $system=TRUE,$exclude_central=TRUE) $this->db->where("repositories.ispublished",1); } - if ($system==FALSE){ + /*if ($system==FALSE){ //show system repositories $this->db->where("repositories.type !=",2); - } + }*/ $this->db->order_by('repository_sections.weight ASC, repositories.weight ASC, repositories.title'); $this->db->join('repository_sections', 'repository_sections.id= repositories.section','inner'); @@ -694,7 +694,7 @@ public function repo_survey_counts_by_data_access($repositoryid,$da_types=NULL) **/ public function repo_survey_list($repositoryid,$data_access_types=NULL) { - $this->db->select('surveys.id,surveys.titl,surveys.nation,surveys.year_start,surveys.year_end,forms.model as da_model,surveys.created,surveys.changed'); + $this->db->select('surveys.id,surveys.title,surveys.nation,surveys.year_start,surveys.year_end,forms.model as da_model,surveys.created,surveys.changed'); $this->db->join('survey_repos', 'surveys.id = survey_repos.sid','inner'); $this->db->join('forms', 'surveys.formid = forms.formid','left'); $this->db->where('survey_repos.repositoryid',$repositoryid); diff --git a/application/schemas/ddi-schema.json b/application/schemas/ddi-schema.json index a0cf59f51..f99ff1751 100644 --- a/application/schemas/ddi-schema.json +++ b/application/schemas/ddi-schema.json @@ -534,10 +534,14 @@ "title":"Keyword", "type":"string" }, + "vocab":{ + "title":"Vocabulary", + "type":"string" + }, "uri":{ "title":"uri", "type":"string" - } + } } } }, diff --git a/application/schemas/image-schema.json b/application/schemas/image-schema.json index 4f5d80648..863b5a338 100644 --- a/application/schemas/image-schema.json +++ b/application/schemas/image-schema.json @@ -81,34 +81,89 @@ } }, "image_description":{ - "allOf": [{ - "$ref": "../schemas/iptc-pmd-schema.json" - }] - }, - "files": { - "type": "array", - "title": "Files", - "description": "Files", - "items":{ - "type":"object", - "properties":{ - "file_uri": { - "title": "File name", - "description":"File name or URL", - "type": "string" - }, - "format": { - "title": "File format", - "description": "The file format, physical medium, or dimensions of the resource.", - "type": "string" - }, - "note": { - "title": "Notes", - "type": "string" + "type": "object", + "properties": { + "iptc": { + "allOf": [{ "$ref": "../schemas/iptc-pmd-schema.json" }] + }, + "license": { + "type": "array", + "title": "License", + "items": { + "type": "object", + "properties": { + "name": { + "title": "License", + "type": "string" + }, + "uri": { + "title": "URI", + "type": "string" + } + } } }, - "required": ["file_uri"] + "album": { + "type": "array", + "title": "Album", + "items": { + "type": "object", + "properties": { + "name": { + "title": "Name of album", + "type": "string" + }, + "description": { + "title": "Description", + "type": "string" + }, + "owner": { + "title": "Owner", + "type": "string" + }, + "uri": { + "title": "URI", + "type": "string" + } + } + } + }, + "files": { + "type": "array", + "title": "Files", + "description": "Files", + "items":{ + "type":"object", + "properties":{ + "file_uri": { + "title": "File name", + "description":"File name or URL", + "type": "string" + }, + "format": { + "title": "File format", + "description": "The file format, physical medium, or dimensions of the resource.", + "type": "string" + }, + "note": { + "title": "Notes", + "type": "string" + }, + "show": { + "title": "Show file (images only)", + "description": "Show the image file on the page", + "type": "boolean" + } + }, + "required": ["file_uri"] + } + } } } - } + }, + "additional": { + "type": "object", + "description": "Additional metadata", + "properties": {} + } } \ No newline at end of file diff --git a/application/schemas/script-schema.json b/application/schemas/script-schema.json index ae0c43a08..f693199d0 100644 --- a/application/schemas/script-schema.json +++ b/application/schemas/script-schema.json @@ -11,34 +11,19 @@ "title": "Collection ID that owns the script", "description": "Abbreviation for the collection that owns the script" }, - - "access_policy": { - "type": "string", - "title": "Data access policy", - "description": "Data access policy for attached microdata resources", - "enum": [ - "direct", - "open", - "public", - "licensed", - "remote", - "na" - ], - "default": "na" - }, - "data_remote_url": { - "type": "string", - "title": "Data website URL", - "description": "Link to the website where the data is available, this is only needed if `access_policy` is set to `remote`.", - "default": "" - }, "published": { "type": "integer", "title": "Status", "description": "Status of the script - 0=draft, 1=published", "default": 0 }, + "overwrite": { + "type": "string", + "description": "Overwrite document if already exists?", + "enum":["yes","no"], + "default": "no" + }, "doc_desc": { "type": "object", @@ -147,18 +132,42 @@ }, "production_date": { - "type": "string", "title":"Date of production (YYYY-MM-DD)", - "description": "Date when the project (dissemination-ready version) was implemented" - }, - "geographic_coverage": { - "title": "Geographic coverage", - "description": "Information on the geographic areas (if any) covered by the scripts/project. This may be a list of countries, regions, etc", + "description": "Date when the project (dissemination-ready version) was implemented", "type": "array", "items": { "type": "string" } }, + + "geographic_units": { + "title": "Geographic locations", + "description": "List of geographic units (regions, countries, states, provinces, etc.) for which data are available in the database.", + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "title": "Location name", + "description": "Name of the geographic unit e.g. 'World', 'Africa', 'Afghanistan'", + "type": "string" + }, + "code": { + "title": "Location code", + "description": "Code of the geographic unit (for countries, preferred = ISO3 code)", + "type": "string" + }, + "type": { + "title": "Type", + "description": "Type of geographic unit e.g. country, state, region, province etc", + "type": "string" + } + }, + "required": [ + "name" + ] + } + }, "authoring_entity": { "type": "array", "title": "Authoring entity", @@ -194,9 +203,9 @@ ] } }, - "contributor": { + "contributors": { "type": "array", - "title": "Contributor(s)", + "title": "Contributors", "description": "The person, corporate body, or agency who contributed to the project.", "items": { "type": "object", @@ -233,10 +242,10 @@ ] } }, - "curator": { + "curators": { "type": "array", - "title": "Contributor(s)", - "description": "The person, corporate body, or agency who contributed to the project.", + "title": "Curators", + "description": "The person, corporate body, or agency who curated to the project.", "items": { "type": "object", "properties": { @@ -276,23 +285,144 @@ "type": "string", "title": "Abstract" }, - "output_type": { - "type": "string", - "title":"Output type", - "description": "Type of output of the script/research project. Example: `On-line interactive data visualization`, `Working paper`" + + "keywords":{ + "title":"Keywords", + "type":"array", + "items":{ + "type":"object", + "properties":{ + "name":{ + "title":"Name", + "type":"string" + }, + "vocabulary":{ + "title":"Vocabulary name", + "type":"string" + }, + "uri":{ + "title":"Vocabulary URI", + "type":"string" + } + } + } }, - "publication_url": { - "type": "string", - "title":"Publication URL", - "description": "Link to the publication (output) to which the scripts are related. This will for example be the URL of a PDF working paper." + + "themes":{ + "title":"Themes", + "type":"array", + "items":{ + "type":"object", + "properties":{ + "name":{ + "title":"Name", + "type":"string" + }, + "vocabulary":{ + "title":"Vocabulary name", + "type":"string" + }, + "uri":{ + "title":"Vocabulary URI", + "type":"string" + } + } + } }, - "doi": { - "type": "string", - "title":"DOI", - "description": "DOI handle" + + "topics": { + "type": "array", + "title": "Topics", + "description": "Topics covered by the table (ideally, the list of topics will be a controlled vocabulary)", + "items": { + "type": "object", + "properties": { + "id": { + "title": "Unique Identifier", + "type": "string" + }, + "name": { + "title": "Topic", + "type": "string" + }, + "parent_id": { + "title": "Parent topic Identifier", + "description":"For subtopics, provide the ID of the parent topic", + "type": "string" + }, + "vocabulary": { + "title": "Vocabulary", + "description": "Name of the controlled vocabulary, if the topic is from a taxonomy.", + "type": "string" + }, + "uri": { + "title": "Vocabulary URI", + "description": "Link to the controlled vocabulary web page, if the topic is from a taxonomy.", + "type": "string" + } + }, + "required": [ + "id","name" + ] + } + }, + + "disciplines": { + "type": "array", + "title": "Disciplines", + "description": "Disciplines e.g. `Social sciences, economics`, `Natural sciences, biology`", + "items": { + "type": "object", + "properties": { + "name": { + "title": "Discipline title or name", + "type": "string" + }, + "vocabulary": { + "title": "Vocabulary", + "description": "Vocabulary", + "type": "string" + }, + "uri": { + "title": "URI", + "description": "Website link", + "type": "string" + } + }, + "required": [ + "name" + ] + } + }, + + "output_types":{ + "title":"Output types", + "description": "Type of outputs of the script/research project. Example: `On-line interactive data visualization`, `Working paper`", + "type":"array", + "items":{ + "type":"object", + "properties":{ + "type":{ + "title":"Type", + "type":"string" + }, + "description":{ + "title":"Description", + "type":"string" + }, + "uri":{ + "title":"URI", + "type":"string" + }, + "doi":{ + "title":"DOI", + "type":"string" + } + } + } }, - "repository_url": { + "repository_uri": { "type": "array", "title": "Source code repository", "description": "Source code repository", @@ -318,59 +448,64 @@ "name" ] } - }, + }, + "project_website": { - "type": "string", - "description": "Project website link" + "title":"Project website", + "description": "Project website link", + "type": "array", + "items": { + "type": "string" + } }, + "version_statement": { "type": "object", "title": "Version Statement", "description": "Version Statement", - "_ddi_xpath":"stdyDscr/citation/verStmt", "properties": { "version": { "title": "Version", - "type": "string", - "_ddi_xpath":"stdyDscr/citation/verStmt/version" + "type": "string" }, "version_date": { "title": "Version Date", - "type": "string", - "_ddi_xpath":"stdyDscr/citation/verStmt/version/@date" + "type": "string" }, "version_resp": { "title": "Version Responsibility Statement", "description":"The organization or person responsible for the version of the work", - "type": "string", - "_ddi_xpath":"stdyDscr/citation/verStmt/verResp" + "type": "string" }, "version_notes": { "title": "Version Notes", - "type": "string", - "_ddi_xpath":"stdyDscr/citation/verStmt/notes" + "type": "string" } } }, "language": { - "type": "object", + "type": "array", "title": "Language", "description": "Documentation language e.g. English, French, etc.", - "properties": { - "name": { - "title": "Name", - "type": "string" + "items": { + "type": "object", + "properties": { + "name": { + "title": "Name", + "type": "string" + }, + "code": { + "title": "Code", + "type": "string" + } }, - "code": { - "title": "Code", - "type": "string" - } - }, - "required": [ - "name" - ] + "required": [ + "name" + ] + } }, + "methods": { "type": "array", "title":"Methods or algorithms applied", @@ -440,36 +575,32 @@ "license": { - "type": "object", - "title": "License", - "description": "License", + "type": "array", + "title": "License", + "items": { + "type": "object", "properties": { "name": { - "title": "Name", + "title": "License", "type": "string" }, - "URI": { + "uri": { "title": "URI", "type": "string" } - }, - "required": [ - "name" - ] + } + } }, - - - - "pub_research": { + "review_process": { "type": "array", - "title": "Published research", - "description": "Published research", + "title": "Review process", + "description": "Review process", "items": { "type": "object", "properties": { - "submit_date": { + "submission_date": { "title": "Date submitted", "type": "string" }, @@ -481,63 +612,18 @@ "title": "Review status", "type": "string" }, - "review_date": { - "title": "Review status", - "type": "string" - }, - "approval_date": { - "title": "Approval date", - "type": "string" - }, "approval_authority": { "title": "Approval authority", "type": "string" }, - "pub_date": { - "title": "Date published", + "approval_date": { + "title": "Date of approval", "type": "string" } } - }, - "required": [ - "name" - ] + } }, - - - "data_included": { - "type": "boolean", - "description": "Is data included with the script?" - }, - "data_url": { - "type": "string", - "description": "Link to an external website where data is available" - }, - "contact": { - "type": "array", - "title": "Contact", - "description": "Contact", - "items": { - "type": "object", - "properties": { - "name": { - "title": "Name", - "type": "string" - }, - "affiliation": { - "title": "Affiliation", - "type": "string" - }, - "URI": { - "title": "URI", - "type": "string" - } - } - }, - "required": [ - "name" - ] - }, + "disclaimer": { "title": "Disclaimer", "type": "string" @@ -548,13 +634,13 @@ }, "citation_requirement": { "type": "string", - "description": "Citation requirements" + "description": "Citation requirements" }, - "data_desc": { + "datasets": { "type": "array", - "title": "Data description", - "description": "Contributors", + "title": "Datasets", + "description": "Datasets used by script", "items": { "type": "object", "properties": { @@ -574,8 +660,9 @@ "title": "Data access policy", "type": "string" }, - "URI": { - "title": "URL", + "uri": { + "title": "URI", + "description": "Link to the website", "type": "string" } } @@ -583,48 +670,9 @@ "required": [ "name" ] - }, - - "review_process": { - "type": "array", - "title": "Project Review Process", - "description": "Project review process that led to the publishing of the scripts", - "items": { - "type": "object", - "properties": { - "submit_date": { - "title": "Submission date", - "type": "string" - }, - "reviewer": { - "title": "Reviewer name", - "type": "string" - }, - "status": { - "title": "Status of review", - "type": "string" - }, - "review_date": { - "title": "Date of review", - "type": "string" - }, - "approval_date": { - "title": "Date of final approval", - "type": "string" - }, - "authority": { - "title": "Authority", - "description":"Identification of the person or organization having formally approved the scripts/project after comlpetion of the review process", - "type": "string" - } - } - }, - "required": [ - "reviewer" - ] - }, + }, - "sponsor": { + "sponsors": { "type": "array", "title": "Sponsor / Funding agency", "description": "The source(s) of funds for production of the work. If different funding agencies sponsored different stages of the production process, use the 'role' attribute to distinguish them.", @@ -642,6 +690,10 @@ "role": { "title": "Role", "type": "string" + }, + "grant_no":{ + "title": "Grant number", + "type": "string" } } }, @@ -649,6 +701,7 @@ "name" ] }, + "acknowledgements": { "type": "array", "title": "Other Identifications /Acknowledgments", @@ -732,10 +785,10 @@ }, - "script_files": { + "scripts": { "type": "array", "title": "Script files", - "description": "Script files", + "description": "Description of each script file", "items": { "type": "object", "properties": { diff --git a/application/views/auth/change_password.php b/application/views/auth/change_password.php index d70d2b87a..f559a0dd1 100644 --- a/application/views/auth/change_password.php +++ b/application/views/auth/change_password.php @@ -15,10 +15,12 @@
    - -

    :
    + + + +

    :
    -

    +

    :
    diff --git a/application/views/auth/create_user.php b/application/views/auth/create_user.php index 71f217497..79aa38be7 100644 --- a/application/views/auth/create_user.php +++ b/application/views/auth/create_user.php @@ -20,7 +20,9 @@

    'form register','autocomplete'=>'off'));?> - + + +
    diff --git a/application/views/auth/login.php b/application/views/auth/login.php index 1f3e006ee..e8d117bf2 100644 --- a/application/views/auth/login.php +++ b/application/views/auth/login.php @@ -16,12 +16,10 @@
    + + + + \ No newline at end of file diff --git a/application/views/reports/public_request_view.php b/application/views/reports/public_request_view.php index 3656519a2..2d018cac5 100644 --- a/application/views/reports/public_request_view.php +++ b/application/views/reports/public_request_view.php @@ -15,11 +15,11 @@ - - - + - - - + diff --git a/application/views/reports/study_statistics.php b/application/views/reports/study_statistics.php index a44f869fc..ee5b8e150 100644 --- a/application/views/reports/study_statistics.php +++ b/application/views/reports/study_statistics.php @@ -14,8 +14,8 @@ } else { - $img_no=''; - $img_yes=''; + $img_no='✖'; + $img_yes='✓'; } ?> @@ -39,7 +39,7 @@ - + diff --git a/application/views/reports/survey_summary.php b/application/views/reports/survey_summary.php index a6ab9879f..6c3767657 100644 --- a/application/views/reports/survey_summary.php +++ b/application/views/reports/survey_summary.php @@ -14,8 +14,8 @@ - - + + diff --git a/application/views/repositories/edit.php b/application/views/repositories/edit.php index ed896f63c..5f3dc72af 100644 --- a/application/views/repositories/edit.php +++ b/application/views/repositories/edit.php @@ -26,8 +26,7 @@ $sections=$this->data['section_options']; $options_section=array(); -foreach($sections as $sec) -{ +foreach($sections as $sec){ $options_section[$sec['id']]=$sec['title']; } ?> diff --git a/application/views/repositories/history.php b/application/views/repositories/history.php index 55244730e..b6b74a90e 100644 --- a/application/views/repositories/history.php +++ b/application/views/repositories/history.php @@ -7,7 +7,7 @@
    :
    - +
    @@ -23,7 +23,7 @@ - +
    #
    titl;?>title;?> nation; ?> + .repo-thumbnail{ + max-width:150px; + } + 'Internal', @@ -89,11 +94,11 @@ - - - - - + + + + + @@ -101,7 +106,8 @@ - + + diff --git a/application/views/repositories/index_public.php b/application/views/repositories/index_public.php index c4e28d25b..dc5368dd8 100644 --- a/application/views/repositories/index_public.php +++ b/application/views/repositories/index_public.php @@ -1,4 +1,3 @@ -
    $section): ?> @@ -14,7 +13,7 @@ ?>
    -

    +

    diff --git a/application/views/repositories/repos_by_section.php b/application/views/repositories/repos_by_section.php index 59d1df008..574a0df44 100644 --- a/application/views/repositories/repos_by_section.php +++ b/application/views/repositories/repos_by_section.php @@ -3,28 +3,31 @@ * * Show repos by section */ -if (!isset($show_unpublished)) -{ +if (!isset($show_unpublished)){ $show_unpublished=FALSE; } ?> -
    ID ID
    repositoryid);?>
    repositoryid); ?> title; ?>
    +
    $row): ?> section!=$section){continue;}?> ispublished && $show_unpublished==FALSE){continue;}?> -
    - - - +
    +
    +
    +
    +
    +
    +

    title; ?>

    +

    short_text; ?>

    +
    +
    +
    -
    -

    title; ?>

    -

    short_text; ?>

    -
    + \ No newline at end of file diff --git a/composer.json b/composer.json index a7faa7dc0..28c578fc0 100644 --- a/composer.json +++ b/composer.json @@ -4,6 +4,7 @@ "mpdf/mpdf": "^7.1", "phpmailer/phpmailer": "^5.2.26", "violet/streaming-json-encoder": "^1.1", - "salsify/json-streaming-parser": "^8.0" + "salsify/json-streaming-parser": "^8.0", + "slim/csrf": "^0.8.3" } } diff --git a/composer.lock b/composer.lock index 9de4d8d4b..747eefa20 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "5efa9b4ad5a4e71a23292047391b52a9", + "content-hash": "4e403dac56dc7bdc2d5965eeba7a8f77", "packages": [ { "name": "justinrainbow/json-schema", @@ -523,6 +523,56 @@ ], "time": "2017-05-11T14:25:49+00:00" }, + { + "name": "slim/csrf", + "version": "0.8.3", + "source": { + "type": "git", + "url": "https://github.com/slimphp/Slim-Csrf.git", + "reference": "5f2bcf5d89adf86dc0455a32bea84d912ab466a7" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/slimphp/Slim-Csrf/zipball/5f2bcf5d89adf86dc0455a32bea84d912ab466a7", + "reference": "5f2bcf5d89adf86dc0455a32bea84d912ab466a7", + "shasum": "" + }, + "require": { + "paragonie/random_compat": "^1.1|^2.0|^9.99", + "php": ">=5.5.0", + "psr/http-message": "^1.0" + }, + "require-dev": { + "phpunit/phpunit": "^4.0", + "slim/slim": "~3.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Slim\\Csrf\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Josh Lockhart", + "email": "hello@joshlockhart.com", + "homepage": "http://joshlockhart.com" + } + ], + "description": "Slim Framework 3 CSRF protection middleware", + "homepage": "http://slimframework.com", + "keywords": [ + "csrf", + "framework", + "middleware", + "slim" + ], + "time": "2018-08-22T16:12:18+00:00" + }, { "name": "violet/streaming-json-encoder", "version": "v1.1.1", diff --git a/logs/index.html b/logs/index.html new file mode 100644 index 000000000..e69de29bb diff --git a/modules/phpmailer/.gitignore b/modules/phpmailer/.gitignore deleted file mode 100644 index 21b6b0fa3..000000000 --- a/modules/phpmailer/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -docs/phpdoc/ -test/message.txt -test/testbootstrap.php diff --git a/modules/phpmailer/.travis.yml b/modules/phpmailer/.travis.yml deleted file mode 100644 index 28f0099f9..000000000 --- a/modules/phpmailer/.travis.yml +++ /dev/null @@ -1,20 +0,0 @@ -language: php -php: - - 5.5 - - 5.4 - - 5.3 -before_install: - - sudo apt-get update -qq - - sudo apt-get install -y -qq postfix -before_script: - - sudo service postfix stop - - smtp-sink -d "%d.%H.%M.%S" localhost:2500 1000 & - - cd test - - cp testbootstrap-dist.php testbootstrap.php - - chmod +x fakesendmail.sh - - sudo mkdir -p /var/qmail/bin - - sudo cp fakesendmail.sh /var/qmail/bin/sendmail - - sudo cp fakesendmail.sh /usr/sbin/sendmail - - echo 'sendmail_path = "/usr/sbin/sendmail -t -i "' | sudo tee "/home/travis/.phpenv/versions/`php -i|grep "PHP Version"|head -n 1|grep -o -P '\d+\.\d+\.\d+.*'`/etc/conf.d/sendmail.ini" -script: - - phpunit phpmailerTest diff --git a/modules/phpmailer/LICENSE b/modules/phpmailer/LICENSE deleted file mode 100644 index f3f1b3b65..000000000 --- a/modules/phpmailer/LICENSE +++ /dev/null @@ -1,504 +0,0 @@ - GNU LESSER GENERAL PUBLIC LICENSE - Version 2.1, February 1999 - - Copyright (C) 1991, 1999 Free Software Foundation, Inc. - 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - -[This is the first released version of the Lesser GPL. It also counts - as the successor of the GNU Library Public License, version 2, hence - the version number 2.1.] - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -Licenses are intended to guarantee your freedom to share and change -free software--to make sure the software is free for all its users. - - This license, the Lesser General Public License, applies to some -specially designated software packages--typically libraries--of the -Free Software Foundation and other authors who decide to use it. You -can use it too, but we suggest you first think carefully about whether -this license or the ordinary General Public License is the better -strategy to use in any particular case, based on the explanations below. - - When we speak of free software, we are referring to freedom of use, -not price. Our General Public Licenses are designed to make sure that -you have the freedom to distribute copies of free software (and charge -for this service if you wish); that you receive source code or can get -it if you want it; that you can change the software and use pieces of -it in new free programs; and that you are informed that you can do -these things. - - To protect your rights, we need to make restrictions that forbid -distributors to deny you these rights or to ask you to surrender these -rights. These restrictions translate to certain responsibilities for -you if you distribute copies of the library or if you modify it. - - For example, if you distribute copies of the library, whether gratis -or for a fee, you must give the recipients all the rights that we gave -you. You must make sure that they, too, receive or can get the source -code. If you link other code with the library, you must provide -complete object files to the recipients, so that they can relink them -with the library after making changes to the library and recompiling -it. And you must show them these terms so they know their rights. - - We protect your rights with a two-step method: (1) we copyright the -library, and (2) we offer you this license, which gives you legal -permission to copy, distribute and/or modify the library. - - To protect each distributor, we want to make it very clear that -there is no warranty for the free library. Also, if the library is -modified by someone else and passed on, the recipients should know -that what they have is not the original version, so that the original -author's reputation will not be affected by problems that might be -introduced by others. - - Finally, software patents pose a constant threat to the existence of -any free program. We wish to make sure that a company cannot -effectively restrict the users of a free program by obtaining a -restrictive license from a patent holder. Therefore, we insist that -any patent license obtained for a version of the library must be -consistent with the full freedom of use specified in this license. - - Most GNU software, including some libraries, is covered by the -ordinary GNU General Public License. This license, the GNU Lesser -General Public License, applies to certain designated libraries, and -is quite different from the ordinary General Public License. We use -this license for certain libraries in order to permit linking those -libraries into non-free programs. - - When a program is linked with a library, whether statically or using -a shared library, the combination of the two is legally speaking a -combined work, a derivative of the original library. The ordinary -General Public License therefore permits such linking only if the -entire combination fits its criteria of freedom. The Lesser General -Public License permits more lax criteria for linking other code with -the library. - - We call this license the "Lesser" General Public License because it -does Less to protect the user's freedom than the ordinary General -Public License. It also provides other free software developers Less -of an advantage over competing non-free programs. These disadvantages -are the reason we use the ordinary General Public License for many -libraries. However, the Lesser license provides advantages in certain -special circumstances. - - For example, on rare occasions, there may be a special need to -encourage the widest possible use of a certain library, so that it becomes -a de-facto standard. To achieve this, non-free programs must be -allowed to use the library. A more frequent case is that a free -library does the same job as widely used non-free libraries. In this -case, there is little to gain by limiting the free library to free -software only, so we use the Lesser General Public License. - - In other cases, permission to use a particular library in non-free -programs enables a greater number of people to use a large body of -free software. For example, permission to use the GNU C Library in -non-free programs enables many more people to use the whole GNU -operating system, as well as its variant, the GNU/Linux operating -system. - - Although the Lesser General Public License is Less protective of the -users' freedom, it does ensure that the user of a program that is -linked with the Library has the freedom and the wherewithal to run -that program using a modified version of the Library. - - The precise terms and conditions for copying, distribution and -modification follow. Pay close attention to the difference between a -"work based on the library" and a "work that uses the library". The -former contains code derived from the library, whereas the latter must -be combined with the library in order to run. - - GNU LESSER GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License Agreement applies to any software library or other -program which contains a notice placed by the copyright holder or -other authorized party saying it may be distributed under the terms of -this Lesser General Public License (also called "this License"). -Each licensee is addressed as "you". - - A "library" means a collection of software functions and/or data -prepared so as to be conveniently linked with application programs -(which use some of those functions and data) to form executables. - - The "Library", below, refers to any such software library or work -which has been distributed under these terms. A "work based on the -Library" means either the Library or any derivative work under -copyright law: that is to say, a work containing the Library or a -portion of it, either verbatim or with modifications and/or translated -straightforwardly into another language. (Hereinafter, translation is -included without limitation in the term "modification".) - - "Source code" for a work means the preferred form of the work for -making modifications to it. For a library, complete source code means -all the source code for all modules it contains, plus any associated -interface definition files, plus the scripts used to control compilation -and installation of the library. - - Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running a program using the Library is not restricted, and output from -such a program is covered only if its contents constitute a work based -on the Library (independent of the use of the Library in a tool for -writing it). Whether that is true depends on what the Library does -and what the program that uses the Library does. - - 1. You may copy and distribute verbatim copies of the Library's -complete source code as you receive it, in any medium, provided that -you conspicuously and appropriately publish on each copy an -appropriate copyright notice and disclaimer of warranty; keep intact -all the notices that refer to this License and to the absence of any -warranty; and distribute a copy of this License along with the -Library. - - You may charge a fee for the physical act of transferring a copy, -and you may at your option offer warranty protection in exchange for a -fee. - - 2. You may modify your copy or copies of the Library or any portion -of it, thus forming a work based on the Library, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices - stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no - charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a - table of data to be supplied by an application program that uses - the facility, other than as an argument passed when the facility - is invoked, then you must make a good faith effort to ensure that, - in the event an application does not supply such function or - table, the facility still operates, and performs whatever part of - its purpose remains meaningful. - - (For example, a function in a library to compute square roots has - a purpose that is entirely well-defined independent of the - application. Therefore, Subsection 2d requires that any - application-supplied function or table used by this function must - be optional: if the application does not supply it, the square - root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Library, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Library, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote -it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library -with the Library (or with a work based on the Library) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may opt to apply the terms of the ordinary GNU General Public -License instead of this License to a given copy of the Library. To do -this, you must alter all the notices that refer to this License, so -that they refer to the ordinary GNU General Public License, version 2, -instead of to this License. (If a newer version than version 2 of the -ordinary GNU General Public License has appeared, then you can specify -that version instead if you wish.) Do not make any other change in -these notices. - - Once this change is made in a given copy, it is irreversible for -that copy, so the ordinary GNU General Public License applies to all -subsequent copies and derivative works made from that copy. - - This option is useful when you wish to copy part of the code of -the Library into a program that is not a library. - - 4. You may copy and distribute the Library (or a portion or -derivative of it, under Section 2) in object code or executable form -under the terms of Sections 1 and 2 above provided that you accompany -it with the complete corresponding machine-readable source code, which -must be distributed under the terms of Sections 1 and 2 above on a -medium customarily used for software interchange. - - If distribution of object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the -source code from the same place satisfies the requirement to -distribute the source code, even though third parties are not -compelled to copy the source along with the object code. - - 5. A program that contains no derivative of any portion of the -Library, but is designed to work with the Library by being compiled or -linked with it, is called a "work that uses the Library". Such a -work, in isolation, is not a derivative work of the Library, and -therefore falls outside the scope of this License. - - However, linking a "work that uses the Library" with the Library -creates an executable that is a derivative of the Library (because it -contains portions of the Library), rather than a "work that uses the -library". The executable is therefore covered by this License. -Section 6 states terms for distribution of such executables. - - When a "work that uses the Library" uses material from a header file -that is part of the Library, the object code for the work may be a -derivative work of the Library even though the source code is not. -Whether this is true is especially significant if the work can be -linked without the Library, or if the work is itself a library. The -threshold for this to be true is not precisely defined by law. - - If such an object file uses only numerical parameters, data -structure layouts and accessors, and small macros and small inline -functions (ten lines or less in length), then the use of the object -file is unrestricted, regardless of whether it is legally a derivative -work. (Executables containing this object code plus portions of the -Library will still fall under Section 6.) - - Otherwise, if the work is a derivative of the Library, you may -distribute the object code for the work under the terms of Section 6. -Any executables containing that work also fall under Section 6, -whether or not they are linked directly with the Library itself. - - 6. As an exception to the Sections above, you may also combine or -link a "work that uses the Library" with the Library to produce a -work containing portions of the Library, and distribute that work -under terms of your choice, provided that the terms permit -modification of the work for the customer's own use and reverse -engineering for debugging such modifications. - - You must give prominent notice with each copy of the work that the -Library is used in it and that the Library and its use are covered by -this License. You must supply a copy of this License. If the work -during execution displays copyright notices, you must include the -copyright notice for the Library among them, as well as a reference -directing the user to the copy of this License. Also, you must do one -of these things: - - a) Accompany the work with the complete corresponding - machine-readable source code for the Library including whatever - changes were used in the work (which must be distributed under - Sections 1 and 2 above); and, if the work is an executable linked - with the Library, with the complete machine-readable "work that - uses the Library", as object code and/or source code, so that the - user can modify the Library and then relink to produce a modified - executable containing the modified Library. (It is understood - that the user who changes the contents of definitions files in the - Library will not necessarily be able to recompile the application - to use the modified definitions.) - - b) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (1) uses at run time a - copy of the library already present on the user's computer system, - rather than copying library functions into the executable, and (2) - will operate properly with a modified version of the library, if - the user installs one, as long as the modified version is - interface-compatible with the version that the work was made with. - - c) Accompany the work with a written offer, valid for at - least three years, to give the same user the materials - specified in Subsection 6a, above, for a charge no more - than the cost of performing this distribution. - - d) If distribution of the work is made by offering access to copy - from a designated place, offer equivalent access to copy the above - specified materials from the same place. - - e) Verify that the user has already received a copy of these - materials or that you have already sent this user a copy. - - For an executable, the required form of the "work that uses the -Library" must include any data and utility programs needed for -reproducing the executable from it. However, as a special exception, -the materials to be distributed need not include anything that is -normally distributed (in either source or binary form) with the major -components (compiler, kernel, and so on) of the operating system on -which the executable runs, unless that component itself accompanies -the executable. - - It may happen that this requirement contradicts the license -restrictions of other proprietary libraries that do not normally -accompany the operating system. Such a contradiction means you cannot -use both them and the Library together in an executable that you -distribute. - - 7. You may place library facilities that are a work based on the -Library side-by-side in a single library together with other library -facilities not covered by this License, and distribute such a combined -library, provided that the separate distribution of the work based on -the Library and of the other library facilities is otherwise -permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work - based on the Library, uncombined with any other library - facilities. This must be distributed under the terms of the - Sections above. - - b) Give prominent notice with the combined library of the fact - that part of it is a work based on the Library, and explaining - where to find the accompanying uncombined form of the same work. - - 8. You may not copy, modify, sublicense, link with, or distribute -the Library except as expressly provided under this License. Any -attempt otherwise to copy, modify, sublicense, link with, or -distribute the Library is void, and will automatically terminate your -rights under this License. However, parties who have received copies, -or rights, from you under this License will not have their licenses -terminated so long as such parties remain in full compliance. - - 9. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Library or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Library (or any work based on the -Library), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Library or works based on it. - - 10. Each time you redistribute the Library (or any work based on the -Library), the recipient automatically receives a license from the -original licensor to copy, distribute, link with or modify the Library -subject to these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties with -this License. - - 11. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Library at all. For example, if a patent -license would not permit royalty-free redistribution of the Library by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any -particular circumstance, the balance of the section is intended to apply, -and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 12. If the distribution and/or use of the Library is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Library under this License may add -an explicit geographical distribution limitation excluding those countries, -so that distribution is permitted only in or among countries not thus -excluded. In such case, this License incorporates the limitation as if -written in the body of this License. - - 13. The Free Software Foundation may publish revised and/or new -versions of the Lesser General Public License from time to time. -Such new versions will be similar in spirit to the present version, -but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Library -specifies a version number of this License which applies to it and -"any later version", you have the option of following the terms and -conditions either of that version or of any later version published by -the Free Software Foundation. If the Library does not specify a -license version number, you may choose any version ever published by -the Free Software Foundation. - - 14. If you wish to incorporate parts of the Library into other free -programs whose distribution conditions are incompatible with these, -write to the author to ask for permission. For software which is -copyrighted by the Free Software Foundation, write to the Free -Software Foundation; we sometimes make exceptions for this. Our -decision will be guided by the two goals of preserving the free status -of all derivatives of our free software and of promoting the sharing -and reuse of software generally. - - NO WARRANTY - - 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY -KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY -AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU -FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR -CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE -LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING -RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A -FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Libraries - - If you develop a new library, and you want it to be of the greatest -possible use to the public, we recommend making it free software that -everyone can redistribute and change. You can do so by permitting -redistribution under these terms (or, alternatively, under the terms of the -ordinary General Public License). - - To apply these terms, attach the following notices to the library. It is -safest to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least the -"copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - -Also add information on how to contact you by electronic and paper mail. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the library, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the - library `Frob' (a library for tweaking knobs) written by James Random Hacker. - - , 1 April 1990 - Ty Coon, President of Vice - -That's all there is to it! - - diff --git a/modules/phpmailer/README.md b/modules/phpmailer/README.md deleted file mode 100644 index 671141da7..000000000 --- a/modules/phpmailer/README.md +++ /dev/null @@ -1,134 +0,0 @@ -# PHPMailer - A full-featured email creation and transfer class for PHP - -Build status: [![Build Status](https://travis-ci.org/Synchro/PHPMailer.png)](https://travis-ci.org/Synchro/PHPMailer) - -## Class Features - -- Probably the world's most popular code for sending email from PHP! -- Used by many open-source projects: Drupal, SugarCRM, Yii, Joomla! and many more -- Integrated SMTP support - send without a local mail server -- Send emails with multiple TOs, CCs, BCCs and REPLY-TOs -- Multipart/alternative emails for mail clients that do not read HTML email -- Support for 8bit, base64, binary, and quoted-printable encoding -- SMTP authentication with LOGIN, PLAIN, NTLM and CRAM-MD5 mechanisms -- Native language support -- Compatible with PHP 5.0 and later -- Much more! - -## Why you might need it - -Many PHP developers utilize email in their code. The only PHP function that supports this is the mail() function. However, it does not provide any assistance for making use of popular features such as HTML-based emails and attachments. - -Formatting email correctly is surprisingly difficult. There are myriad overlapping RFCs, requiring tight adherence to horribly complicated formatting and encoding rules - the vast majority of code that you'll find online that uses the mail() function directly is just plain wrong! -*Please* don't be tempted to do it yourself - if you don't use PHPMailer, there are many other excellent libraries that you should look at before rolling your own - try SwiftMailer, Zend_Mail, eZcomponents etc. - -The PHP mail() function usually sends via a local mail server, typically fronted by a `sendmail` binary on Linux, BSD and OS X platforms, however, Windows usually doesn't include a local mail server; PHPMailer's integrated SMTP implementation allows email sending on Windows platforms without a local mail server. - -## License - -This software is licenced under the [LGPL 2.1](http://www.gnu.org/licenses/lgpl-2.1.html). Please read LICENSE for information on the -software availability and distribution. - -## Installation - -PHPMailer is available via [Composer/Packagist](https://packagist.org/packages/phpmailer/phpmailer). Alternatively, just copy the contents of the PHPMailer folder into somewhere that's in your PHP `include_path` setting. If you don't speak git or just want a tarball, click the 'zip' button at the top of the page in GitHub. - - -## A Simple Example - -```php -IsSMTP(); // Set mailer to use SMTP -$mail->Host = 'smtp1.example.com;smtp2.example.com'; // Specify main and backup server -$mail->SMTPAuth = true; // Enable SMTP authentication -$mail->Username = 'jswan'; // SMTP username -$mail->Password = 'secret'; // SMTP password -$mail->SMTPSecure = 'tls'; // Enable encryption, 'ssl' also accepted - -$mail->From = 'from@example.com'; -$mail->FromName = 'Mailer'; -$mail->AddAddress('josh@example.net', 'Josh Adams'); // Add a recipient -$mail->AddAddress('ellen@example.com'); // Name is optional -$mail->AddReplyTo('info@example.com', 'Information'); -$mail->AddCC('cc@example.com'); -$mail->AddBCC('bcc@example.com'); - -$mail->WordWrap = 50; // Set word wrap to 50 characters -$mail->AddAttachment('/var/tmp/file.tar.gz'); // Add attachments -$mail->AddAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name -$mail->IsHTML(true); // Set email format to HTML - -$mail->Subject = 'Here is the subject'; -$mail->Body = 'This is the HTML message body in bold!'; -$mail->AltBody = 'This is the body in plain text for non-HTML mail clients'; - -if(!$mail->Send()) { - echo 'Message could not be sent.'; - echo 'Mailer Error: ' . $mail->ErrorInfo; - exit; -} - -echo 'Message has been sent'; -``` - -You'll find plenty more to play with in the `examples` folder. - -That's it. You should now be ready to use PHPMailer! - -## Localization -PHPMailer defaults to English, but in the `languages` folder you'll find numerous translations for PHPMailer error messages that you may encounter. Their filenames contain [ISO 639-1](http://en.wikipedia.org/wiki/ISO_639-1) language code for the translations, for example `fr` for French. To specify a language, you need to tell PHPMailer which one to use, like this: - -```php -// To load the French version -$mail->SetLanguage('fr', '/optional/path/to/language/directory/'); -``` - -## Documentation - -You'll find some basic user-level docs in the docs folder, and you can generate complete API-level documentation using the `generatedocs.sh` shell script in the docs folder, though you'll need to install [PHPDocumentor](http://www.phpdoc.org) first. - -## Tests - -You'll find a PHPUnit test script in the `test` folder. - -Build status: [![Build Status](https://travis-ci.org/PHPMailer/PHPMailer.png)](https://travis-ci.org/PHPMailer/PHPMailer) - -If this isn't passing, is there something you can do to help? - -## Contributing - -Please submit bug reports, suggestions and pull requests to the [GitHub issue tracker](https://github.com/PHPMailer/PHPMailer/issues). - -We're particularly interested in fixing edge-cases, expanding test coverage and updating translations. - -With the move to the PHPMailer GitHub organisation, you'll need to update any remote URLs referencing the old GitHub location with a command like this from within your clone: - -git remote set-url upstream https://github.com/PHPMailer/PHPMailer.git - -Please *don't* use the SourceForge or Google Code projects any more. - -## Changelog - -See changelog.md - -## History -- PHPMailer was originally written in 2001 by Brent R. Matzelle as a [SourceForge project](http://sourceforge.net/projects/phpmailer/). -- Marcus Bointon (coolbru on SF) and Andy Prevost (codeworxtech) took over the project in 2004. -- Became an Apache incubator project on Google Code in 2010, managed by Jim Jagielski. -- Marcus created his fork on [GitHub](https://github.com/Synchro/PHPMailer). -- Jim and Marcus decide to join forces and use GitHub as the canonical and official repo for PHPMailer. -- PHPMailer moves to the [PHPMailer organisation](https://github.com/PHPMailer) on GitHub. - -### What's changed since moving from SourceForge? -- Official successor to the SourceForge and Google Code projects. -- Test suite. -- Continuous integration with Travis-CI. -- Composer support. -- Rolling releases. -- Additional languages and language strings. -- CRAM-MD5 authentication support. -- Preserves full repo history of authors, commits and branches from the original SourceForge project. diff --git a/modules/phpmailer/changelog.md b/modules/phpmailer/changelog.md deleted file mode 100644 index dbbcc7ac8..000000000 --- a/modules/phpmailer/changelog.md +++ /dev/null @@ -1,501 +0,0 @@ -# ChangeLog - -## Version 5.2.6 (April 11th 2013) -* Reflect move to PHPMailer GitHub organisation at https://github.com/PHPMailer/PHPMailer -* Fix unbumped version numbers -* Update packagist.org with new location -* Clean up Changelog - -## Version 5.2.5 (April 6th 2013) -* First official release after move from Google Code -* Fixes for qmail when sending via mail() -* Merge in changes from Google code 5.2.4 release -* Minor coding standards cleanup in SMTP class -* Improved unit tests, now tests S/MIME signing -* Travis-CI support on GitHub, runs tests with fake SMTP server - -## Version 5.2.4 (February 19, 2013) -* Fix tag and version bug. -* un-deprecate isSMTP(), isMail(), IsSendmail() and - isQmail(). -* Numerous translation updates - -## Version 5.2.3 (February 8, 2013) -* Fix issue with older PCREs and ValidateAddress() (Bugz: 124) -* Add CRAM-MD5 authentication, thanks to Elijah madden, https://github.com/okonomiyaki3000 -* Replacement of obsolete Quoted-Printable encoder with a much better implementation -* Composer package definition -* New language added: Hebrew - -## Version 5.2.2 (December 3, 2012) -* Some fixes and syncs from https://github.com/Synchro/PHPMailer -* Add Slovak translation, thanks to Michal Tinka - -## Version 5.2.2-rc2 (November 6, 2012) -* Fix SMTP server rotation (Bugz: 118) -* Allow override of autogen'ed 'Date' header (for Drupal's - og_mailinglist module) -* No whitespace after '-f' option (Bugz: 116) -* Work around potential warning (Bugz: 114) - -## Version 5.2.2-rc1 (September 28, 2012) -* Header encoding works with long lines (Bugz: 93) -* Turkish language update (Bugz: 94) -* undefined $pattern in EncodeQ bug squashed (Bugz: 98) -* use of mail() in safe_mode now works (Bugz: 96) -* ValidateAddress() now 'public static' so people can override the - default and use their own validation scheme. -* ValidateAddress() no longer uses broken FILTER_VALIDATE_EMAIL -* Added in AUTH PLAIN SMTP authentication - -## Version 5.2.2-beta2 (August 17, 2012) -* Fixed Postfix VERP support (Bugz: 92) -* Allow action_function callbacks to pass/use - the From address (passed as final param) -* Prevent inf look for get_lines() (Bugz: 77) -* New public var ($UseSendmailOptions). Only pass sendmail() - options iff we really are using sendmail or something sendmail - compatible. (Bugz: 75) -* default setting for LE returned to "\n" due to popular demand. - -## Version 5.2.2-beta1 (July 13, 2012) -* Expose PreSend() and PostSend() as public methods to allow - for more control if serializing message sending. -* GetSentMIMEMessage() only constructs the message copy when - needed. Save memory. -* Only pass params to mail() if the underlying MTA is - "sendmail" (as defined as "having the string sendmail - in its pathname") [#69] -* Attachments now work with Amazon SES and others [Bugz#70] -* Debug output now sent to stdout (via echo) or error_log [Bugz#5] -* New var: Debugoutput (for above) [Bugz#5] -* SMTP reads now Timeout aware (new var: Timeout=15) [Bugz#71] -* SMTP reads now can have a Timelimit associated with them - (new var: Timelimit=30)[Bugz#71] -* Fix quoting issue associated with charsets -* default setting for LE is now RFC compliant: "\r\n" -* Return-Path can now be user defined (new var: ReturnPath) - (the default is "" which implies no change from previous - behavior, which was to use either From or Sender) [Bugz#46] -* X-Mailer header can now be disabled (by setting to a - whitespace string, eg " ") [Bugz#66] -* Bugz closed: #68, #60, #42, #43, #59, #55, #66, #48, #49, - #52, #31, #41, #5. #70, #69 - -## Version 5.2.1 (January 16, 2012) -* Closed several bugs#5 -* Performance improvements -* MsgHTML() now returns the message as required. -* New method: GetSentMIMEMessage() (returns full copy of sent message) - -## Version 5.2 (July 19, 2011) -* protected MIME body and header -* better DKIM DNS Resource Record support -* better aly handling -* htmlfilter class added to extras -* moved to Apache Extras - -## Version 5.1 (October 20, 2009) -* fixed filename issue with AddStringAttachment (thanks to Tony) -* fixed "SingleTo" property, now works with Senmail, Qmail, and SMTP in - addition to PHP mail() -* added DKIM digital signing functionality, new properties: - - DKIM_domain (sets the domain name) - - DKIM_private (holds DKIM private key) - - DKIM_passphrase (holds your DKIM passphrase) - - DKIM_selector (holds the DKIM "selector") - - DKIM_identity (holds the identifying email address) -* added callback function support - - callback function parameters include: - result, to, cc, bcc, subject and body - - see the test/test_callback.php file for usage. -* added "auto" identity functionality - - can automatically add: - - Return-path (if Sender not set) - - Reply-To (if ReplyTo not set) - - can be disabled: - - $mail->SetFrom('yourname@yourdomain.com','First Last',false); - - or by adding the $mail->Sender and/or $mail->ReplyTo properties - -Note: "auto" identity added to help with emails ending up in spam or junk boxes because of missing headers - -## Version 5.0.2 (May 24, 2009) -* Fix for missing attachments when inline graphics are present -* Fix for missing Cc in header when using SMTP (mail was sent, - but not displayed in header -- Cc receiver only saw email To: - line and no Cc line, but did get the email (To receiver - saw same) - -## Version 5.0.1 (April 05, 2009) -* Temporary fix for missing attachments - -## Version 5.0.0 (April 02, 2009) -With the release of this version, we are initiating a new version numbering -system to differentiate from the PHP4 version of PHPMailer. -Most notable in this release is fully object oriented code. - -### class.smtp.php: -* Refactored class.smtp.php to support new exception handling -* code size reduced from 29.2 Kb to 25.6 Kb -* Removed unnecessary functions from class.smtp.php: - - public function Expand($name) { - - public function Help($keyword="") { - - public function Noop() { - - public function Send($from) { - - public function SendOrMail($from) { - - public function Verify($name) { - -### class.phpmailer.php: -* Refactored class.phpmailer.php with new exception handling -* Changed processing functionality of Sendmail and Qmail so they cannot be - inadvertently used -* removed getFile() function, just became a simple wrapper for - file_get_contents() -* added check for PHP version (will gracefully exit if not at least PHP 5.0) -* enhanced code to check if an attachment source is the same as an embedded or - inline graphic source to eliminate duplicate attachments - -### New /test_script -We have written a test script you can use to test the script as part of your -installation. Once you press submit, the test script will send a multi-mime -email with either the message you type in or an HTML email with an inline -graphic. Two attachments are included in the email (one of the attachments -is also the inline graphic so you can see that only one copy of the graphic -is sent in the email). The test script will also display the functional -script that you can copy/paste to your editor to duplicate the functionality. - -### New examples -All new examples in both basic and advanced modes. Advanced examples show - Exception handling. - -### PHPDocumentator (phpdocs) documentation for PHPMailer version 5.0.0 -All new documentation - -## Version 2.3 (November 06, 2008) -* added Arabic language (many thanks to Bahjat Al Mostafa) -* removed English language from language files and made it a default within - class.phpmailer.php - if no language is found, it will default to use - the english language translation -* fixed public/private declarations -* corrected line 1728, $basedir to $directory -* added $sign_cert_file to avoid improper duplicate use of $sign_key_file -* corrected $this->Hello on line 612 to $this->Helo -* changed default of $LE to "\r\n" to comply with RFC 2822. Can be set by the user - if default is not acceptable -* removed trim() from return results in EncodeQP -* /test and three files it contained are removed from version 2.3 -* fixed phpunit.php for compliance with PHP5 -* changed $this->AltBody = $textMsg; to $this->AltBody = html_entity_decode($textMsg); -* We have removed the /phpdoc from the downloads. All documentation is now on - the http://phpmailer.codeworxtech.com website. - -## Version 2.2.1 () July 19 2008 -* fixed line 1092 in class.smtp.php (my apologies, error on my part) - -## Version 2.2 () July 15 2008 -* Fixed redirect issue (display of UTF-8 in thank you redirect) -* fixed error in getResponse function declaration (class.pop3.php) -* PHPMailer now PHP6 compliant -* fixed line 1092 in class.smtp.php (endless loop from missing = sign) - -## Version 2.1 (Wed, June 04 2008) -NOTE: WE HAVE A NEW LANGUAGE VARIABLE FOR DIGITALLY SIGNED S/MIME EMAILS. IF YOU CAN HELP WITH LANGUAGES OTHER THAN ENGLISH AND SPANISH, IT WOULD BE APPRECIATED. - -* added S/MIME functionality (ability to digitally sign emails) - BIG THANKS TO "sergiocambra" for posting this patch back in November 2007. - The "Signed Emails" functionality adds the Sign method to pass the private key - filename and the password to read it, and then email will be sent with - content-type multipart/signed and with the digital signature attached. -* fully compatible with E_STRICT error level - - Please note: - In about half the test environments this development version was subjected - to, an error was thrown for the date() functions used (line 1565 and 1569). - This is NOT a PHPMailer error, it is the result of an incorrectly configured - PHP5 installation. The fix is to modify your 'php.ini' file and include the - date.timezone = America/New York - directive, to your own server timezone - - If you do get this error, and are unable to access your php.ini file: - In your PHP script, add - `date_default_timezone_set('America/Toronto');` - - do not try to use - `$myVar = date_default_timezone_get();` - as a test, it will throw an error. -* added ability to define path (mainly for embedded images) - function `MsgHTML($message,$basedir='')` ... where: - `$basedir` is the fully qualified path -* fixed `MsgHTML()` function: - - Embedded Images where images are specified by `://` will not be altered or embedded -* fixed the return value of SMTP exit code ( pclose ) -* addressed issue of multibyte characters in subject line and truncating -* added ability to have user specified Message ID - (default is still that PHPMailer create a unique Message ID) -* corrected unidentified message type to 'application/octet-stream' -* fixed chunk_split() multibyte issue (thanks to Colin Brown, et al). -* added check for added attachments -* enhanced conversion of HTML to text in MsgHTML (thanks to "brunny") - -## Version 2.1.0beta2 (Sun, Dec 02 2007) -* implemented updated EncodeQP (thanks to coolbru, aka Marcus Bointon) -* finished all testing, all known bugs corrected, enhancements tested - -Note: will NOT work with PHP4. - -Please note, this is BETA software **DO NOT USE THIS IN PRODUCTION OR LIVE PROJECTS; INTENDED STRICTLY FOR TESTING** - -## Version 2.1.0beta1 -Please note, this is BETA software -** DO NOT USE THIS IN PRODUCTION OR LIVE PROJECTS - INTENDED STRICTLY FOR TESTING - -## Version 2.0.0 rc2 (Fri, Nov 16 2007), interim release -* implements new property to control VERP in class.smtp.php - example (requires instantiating class.smtp.php): - $mail->do_verp = true; -* POP-before-SMTP functionality included, thanks to Richard Davey - (see class.pop3.php & pop3_before_smtp_test.php for examples) -* included example showing how to use PHPMailer with GMAIL -* fixed the missing Cc in SendMail() and Mail() - -****************** -A note on sending bulk emails: - -If the email you are sending is not personalized, consider using the -"undisclosed-recipient:;" strategy. That is, put all of your recipients -in the Bcc field and set the To field to "undisclosed-recipients:;". -It's a lot faster (only one send) and saves quite a bit on resources. -Contrary to some opinions, this will not get you listed in spam engines - -it's a legitimate way for you to send emails. - -A partial example for use with PHPMailer: - -``` -$mail->AddAddress("undisclosed-recipients:;"); -$mail->AddBCC("email1@anydomain.com,email2@anyotherdomain.com,email3@anyalternatedomain.com"); -``` - -Many email service providers restrict the number of emails that can be sent -in any given time period. Often that is between 50 - 60 emails maximum -per hour or per send session. - -If that's the case, then break up your Bcc lists into chunks that are one -less than your limit, and put a pause in your script. -******************* - -## Version 2.0.0 rc1 (Thu, Nov 08 2007), interim release -* dramatically simplified using inline graphics ... it's fully automated and requires no user input -* added automatic document type detection for attachments and pictures -* added MsgHTML() function to replace Body tag for HTML emails -* fixed the SendMail security issues (input validation vulnerability) -* enhanced the AddAddresses functionality so that the "Name" portion is used in the email address -* removed the need to use the AltBody method (set from the HTML, or default text used) -* set the PHP Mail() function as the default (still support SendMail, SMTP Mail) -* removed the need to set the IsHTML property (set automatically) -* added Estonian language file by Indrek Päri -* added header injection patch -* added "set" method to permit users to create their own pseudo-properties like 'X-Headers', etc. - example of use: - -``` -$mail->set('X-Priority', '3'); -$mail->set('X-MSMail-Priority', 'Normal'); -``` - -* fixed warning message in SMTP get_lines method -* added TLS/SSL SMTP support. Example of use: - -``` -$mail = new PHPMailer(); -$mail->Mailer = "smtp"; -$mail->Host = "smtp.example.com"; -$mail->SMTPSecure = "tls"; // option -//$mail->SMTPSecure = "ssl"; // option -... -$mail->Send(); -``` - -* PHPMailer has been tested with PHP4 (4.4.7) and PHP5 (5.2.7) -* Works with PHP installed as a module or as CGI-PHP -NOTE: will NOT work with PHP5 in E_STRICT error mode - -## Version 1.73 (Sun, Jun 10 2005) -* Fixed denial of service bug: http://www.cybsec.com/vuln/PHPMailer-DOS.pdf -* Now has a total of 20 translations -* Fixed alt attachments bug: http://tinyurl.com/98u9k - -## Version 1.72 (Wed, May 25 2004) -* Added Dutch, Swedish, Czech, Norwegian, and Turkish translations. -* Received: Removed this method because spam filter programs like - SpamAssassin reject this header. -* Fixed error count bug. -* SetLanguage default is now "language/". -* Fixed magic_quotes_runtime bug. - -## Version 1.71 (Tue, Jul 28 2003) -* Made several speed enhancements -* Added German and Italian translation files -* Fixed HELO/AUTH bugs on keep-alive connects -* Now provides an error message if language file does not load -* Fixed attachment EOL bug -* Updated some unclear documentation -* Added additional tests and improved others - -## Version 1.70 (Mon, Jun 20 2003) -* Added SMTP keep-alive support -* Added IsError method for error detection -* Added error message translation support (SetLanguage) -* Refactored many methods to increase library performance -* Hello now sends the newer EHLO message before HELO as per RFC 2821 -* Removed the boundary class and replaced it with GetBoundary -* Removed queue support methods -* New $Hostname variable -* New Message-ID header -* Received header reformat -* Helo variable default changed to $Hostname -* Removed extra spaces in Content-Type definition (#667182) -* Return-Path should be set to Sender when set -* Adds Q or B encoding to headers when necessary -* quoted-encoding should now encode NULs \000 -* Fixed encoding of body/AltBody (#553370) -* Adds "To: undisclosed-recipients:;" when all recipients are hidden (BCC) -* Multiple bug fixes - -## Version 1.65 (Fri, Aug 09 2002) -* Fixed non-visible attachment bug (#585097) for Outlook -* SMTP connections are now closed after each transaction -* Fixed SMTP::Expand return value -* Converted SMTP class documentation to phpDocumentor format - -## Version 1.62 (Wed, Jun 26 2002) -* Fixed multi-attach bug -* Set proper word wrapping -* Reduced memory use with attachments -* Added more debugging -* Changed documentation to phpDocumentor format - -## Version 1.60 (Sat, Mar 30 2002) -* Sendmail pipe and address patch (Christian Holtje) -* Added embedded image and read confirmation support (A. Ognio) -* Added unit tests -* Added SMTP timeout support (*nix only) -* Added possibly temporary PluginDir variable for SMTP class -* Added LE message line ending variable -* Refactored boundary and attachment code -* Eliminated SMTP class warnings -* Added SendToQueue method for future queuing support - -## Version 1.54 (Wed, Dec 19 2001) -* Add some queuing support code -* Fixed a pesky multi/alt bug -* Messages are no longer forced to have "To" addresses - -## Version 1.50 (Thu, Nov 08 2001) -* Fix extra lines when not using SMTP mailer -* Set WordWrap variable to int with a zero default - -## Version 1.47 (Tue, Oct 16 2001) -* Fixed Received header code format -* Fixed AltBody order error -* Fixed alternate port warning - -## Version 1.45 (Tue, Sep 25 2001) -* Added enhanced SMTP debug support -* Added support for multiple ports on SMTP -* Added Received header for tracing -* Fixed AddStringAttachment encoding -* Fixed possible header name quote bug -* Fixed wordwrap() trim bug -* Couple other small bug fixes - -## Version 1.41 (Wed, Aug 22 2001) -* Fixed AltBody bug w/o attachments -* Fixed rfc_date() for certain mail servers - -## Version 1.40 (Sun, Aug 12 2001) -* Added multipart/alternative support (AltBody) -* Documentation update -* Fixed bug in Mercury MTA - -## Version 1.29 (Fri, Aug 03 2001) -* Added AddStringAttachment() method -* Added SMTP authentication support - -## Version 1.28 (Mon, Jul 30 2001) -* Fixed a typo in SMTP class -* Fixed header issue with Imail (win32) SMTP server -* Made fopen() calls for attachments use "rb" to fix win32 error - -## Version 1.25 (Mon, Jul 02 2001) -* Added RFC 822 date fix (Patrice) -* Added improved error handling by adding a $ErrorInfo variable -* Removed MailerDebug variable (obsolete with new error handler) - -## Version 1.20 (Mon, Jun 25 2001) -* Added quoted-printable encoding (Patrice) -* Set Version as public and removed PrintVersion() -* Changed phpdoc to only display public variables and methods - -## Version 1.19 (Thu, Jun 21 2001) -* Fixed MS Mail header bug -* Added fix for Bcc problem with mail(). *Does not work on Win32* - (See PHP bug report: http://www.php.net/bugs.php?id=11616) -* mail() no longer passes a fifth parameter when not needed - -## Version 1.15 (Fri, Jun 15 2001) -Note: these changes contributed by Patrice Fournier -* Changed all remaining \n to \r\n -* Bcc: header no longer writen to message except - when sent directly to sendmail -* Added a small message to non-MIME compliant mail reader -* Added Sender variable to change the Sender email - used in -f for sendmail/mail and in 'MAIL FROM' for smtp mode -* Changed boundary setting to a place it will be set only once -* Removed transfer encoding for whole message when using multipart -* Message body now uses Encoding in multipart messages -* Can set encoding and type to attachments 7bit, 8bit - and binary attachment are sent as is, base64 are encoded -* Can set Encoding to base64 to send 8 bits body - through 7 bits servers - -## Version 1.10 (Tue, Jun 12 2001) -* Fixed win32 mail header bug (printed out headers in message body) - -## Version 1.09 (Fri, Jun 08 2001) -* Changed date header to work with Netscape mail programs -* Altered phpdoc documentation - -## Version 1.08 (Tue, Jun 05 2001) -* Added enhanced error-checking -* Added phpdoc documentation to source - -## Version 1.06 (Fri, Jun 01 2001) -* Added optional name for file attachments - -## Version 1.05 (Tue, May 29 2001) -* Code cleanup -* Eliminated sendmail header warning message -* Fixed possible SMTP error - -## Version 1.03 (Thu, May 24 2001) -* Fixed problem where qmail sends out duplicate messages - -## Version 1.02 (Wed, May 23 2001) -* Added multiple recipient and attachment Clear* methods -* Added Sendmail public variable -* Fixed problem with loading SMTP library multiple times - -## Version 0.98 (Tue, May 22 2001) -* Fixed problem with redundant mail hosts sending out multiple messages -* Added additional error handler code -* Added AddCustomHeader() function -* Added support for Microsoft mail client headers (affects priority) -* Fixed small bug with Mailer variable -* Added PrintVersion() function - -## Version 0.92 (Tue, May 15 2001) -* Changed file names to class.phpmailer.php and class.smtp.php to match - current PHP class trend. -* Fixed problem where body not being printed when a message is attached -* Several small bug fixes - -## Version 0.90 (Tue, April 17 2001) -* Initial public release diff --git a/modules/phpmailer/class.phpmailer.php b/modules/phpmailer/class.phpmailer.php deleted file mode 100644 index 667f18788..000000000 --- a/modules/phpmailer/class.phpmailer.php +++ /dev/null @@ -1,2810 +0,0 @@ -UseSendmailOptions) ) { - $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($subject)), $body, $header); - } else { - $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($subject)), $body, $header, $params); - } - return $rt; - } - - /** - * Outputs debugging info via user-defined method - * @param string $str - */ - private function edebug($str) { - if ($this->Debugoutput == "error_log") { - error_log($str); - } else { - echo $str; - } - } - - /** - * Constructor - * @param boolean $exceptions Should we throw external exceptions? - */ - public function __construct($exceptions = false) { - $this->exceptions = ($exceptions == true); - } - - /** - * Destructor - */ - public function __destruct() { - if ($this->Mailer == 'smtp') { //Close any open SMTP connection nicely - $this->SmtpClose(); - } - } - - /** - * Sets message type to HTML. - * @param bool $ishtml - * @return void - */ - public function IsHTML($ishtml = true) { - if ($ishtml) { - $this->ContentType = 'text/html'; - } else { - $this->ContentType = 'text/plain'; - } - } - - /** - * Sets Mailer to send message using SMTP. - * @return void - */ - public function IsSMTP() { - $this->Mailer = 'smtp'; - } - - /** - * Sets Mailer to send message using PHP mail() function. - * @return void - */ - public function IsMail() { - $this->Mailer = 'mail'; - } - - /** - * Sets Mailer to send message using the $Sendmail program. - * @return void - */ - public function IsSendmail() { - if (!stristr(ini_get('sendmail_path'), 'sendmail')) { - $this->Sendmail = '/var/qmail/bin/sendmail'; - } - $this->Mailer = 'sendmail'; - } - - /** - * Sets Mailer to send message using the qmail MTA. - * @return void - */ - public function IsQmail() { - if (stristr(ini_get('sendmail_path'), 'qmail')) { - $this->Sendmail = '/var/qmail/bin/sendmail'; - } - $this->Mailer = 'sendmail'; - } - - ///////////////////////////////////////////////// - // METHODS, RECIPIENTS - ///////////////////////////////////////////////// - - /** - * Adds a "To" address. - * @param string $address - * @param string $name - * @return boolean true on success, false if address already used - */ - public function AddAddress($address, $name = '') { - return $this->AddAnAddress('to', $address, $name); - } - - /** - * Adds a "Cc" address. - * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer. - * @param string $address - * @param string $name - * @return boolean true on success, false if address already used - */ - public function AddCC($address, $name = '') { - return $this->AddAnAddress('cc', $address, $name); - } - - /** - * Adds a "Bcc" address. - * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer. - * @param string $address - * @param string $name - * @return boolean true on success, false if address already used - */ - public function AddBCC($address, $name = '') { - return $this->AddAnAddress('bcc', $address, $name); - } - - /** - * Adds a "Reply-to" address. - * @param string $address - * @param string $name - * @return boolean - */ - public function AddReplyTo($address, $name = '') { - return $this->AddAnAddress('Reply-To', $address, $name); - } - - /** - * Adds an address to one of the recipient arrays - * Addresses that have been added already return false, but do not throw exceptions - * @param string $kind One of 'to', 'cc', 'bcc', 'ReplyTo' - * @param string $address The email address to send to - * @param string $name - * @throws phpmailerException - * @return boolean true on success, false if address already used or invalid in some way - * @access protected - */ - protected function AddAnAddress($kind, $address, $name = '') { - if (!preg_match('/^(to|cc|bcc|Reply-To)$/', $kind)) { - $this->SetError($this->Lang('Invalid recipient array').': '.$kind); - if ($this->exceptions) { - throw new phpmailerException('Invalid recipient array: ' . $kind); - } - if ($this->SMTPDebug) { - $this->edebug($this->Lang('Invalid recipient array').': '.$kind); - } - return false; - } - $address = trim($address); - $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim - if (!$this->ValidateAddress($address)) { - $this->SetError($this->Lang('invalid_address').': '. $address); - if ($this->exceptions) { - throw new phpmailerException($this->Lang('invalid_address').': '.$address); - } - if ($this->SMTPDebug) { - $this->edebug($this->Lang('invalid_address').': '.$address); - } - return false; - } - if ($kind != 'Reply-To') { - if (!isset($this->all_recipients[strtolower($address)])) { - array_push($this->$kind, array($address, $name)); - $this->all_recipients[strtolower($address)] = true; - return true; - } - } else { - if (!array_key_exists(strtolower($address), $this->ReplyTo)) { - $this->ReplyTo[strtolower($address)] = array($address, $name); - return true; - } - } - return false; -} - - /** - * Set the From and FromName properties - * @param string $address - * @param string $name - * @param int $auto Also set Reply-To and Sender - * @throws phpmailerException - * @return boolean - */ - public function SetFrom($address, $name = '', $auto = 1) { - $address = trim($address); - $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim - if (!$this->ValidateAddress($address)) { - $this->SetError($this->Lang('invalid_address').': '. $address); - if ($this->exceptions) { - throw new phpmailerException($this->Lang('invalid_address').': '.$address); - } - if ($this->SMTPDebug) { - $this->edebug($this->Lang('invalid_address').': '.$address); - } - return false; - } - $this->From = $address; - $this->FromName = $name; - if ($auto) { - if (empty($this->ReplyTo)) { - $this->AddAnAddress('Reply-To', $address, $name); - } - if (empty($this->Sender)) { - $this->Sender = $address; - } - } - return true; - } - - /** - * Check that a string looks roughly like an email address should - * Static so it can be used without instantiation, public so people can overload - * Conforms to RFC5322: Uses *correct* regex on which FILTER_VALIDATE_EMAIL is - * based; So why not use FILTER_VALIDATE_EMAIL? Because it was broken to - * not allow a@b type valid addresses :( - * @link http://squiloople.com/2009/12/20/email-address-validation/ - * @copyright regex Copyright Michael Rushton 2009-10 | http://squiloople.com/ | Feel free to use and redistribute this code. But please keep this copyright notice. - * @param string $address The email address to check - * @return boolean - * @static - * @access public - */ - public static function ValidateAddress($address) { - if (defined('PCRE_VERSION')) { //Check this instead of extension_loaded so it works when that function is disabled - if (version_compare(PCRE_VERSION, '8.0') >= 0) { - return (boolean)preg_match('/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD', $address); - } else { - //Fall back to an older regex that doesn't need a recent PCRE - return (boolean)preg_match('/^(?!(?>"?(?>\\\[ -~]|[^"])"?){255,})(?!(?>"?(?>\\\[ -~]|[^"])"?){65,}@)(?>[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*")(?>\.(?>[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*"))*@(?>(?![a-z0-9-]{64,})(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>\.(?![a-z0-9-]{64,})(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)){0,126}|\[(?:(?>IPv6:(?>(?>[a-f0-9]{1,4})(?>:[a-f0-9]{1,4}){7}|(?!(?:.*[a-f0-9][:\]]){8,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?::(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?))|(?>(?>IPv6:(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){5}:|(?!(?:.*[a-f0-9]:){6,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4})?::(?>(?:[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4}):)?))?(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?>\.(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}))\])$/isD', $address); - } - } else { - //No PCRE! Do something _very_ approximate! - //Check the address is 3 chars or longer and contains an @ that's not the first or last char - return (strlen($address) >= 3 and strpos($address, '@') >= 1 and strpos($address, '@') != strlen($address) - 1); - } - } - - ///////////////////////////////////////////////// - // METHODS, MAIL SENDING - ///////////////////////////////////////////////// - - /** - * Creates message and assigns Mailer. If the message is - * not sent successfully then it returns false. Use the ErrorInfo - * variable to view description of the error. - * @throws phpmailerException - * @return bool - */ - public function Send() { - try { - if(!$this->PreSend()) return false; - return $this->PostSend(); - } catch (phpmailerException $e) { - $this->mailHeader = ''; - $this->SetError($e->getMessage()); - if ($this->exceptions) { - throw $e; - } - return false; - } - } - - /** - * Prep mail by constructing all message entities - * @throws phpmailerException - * @return bool - */ - public function PreSend() { - try { - $this->mailHeader = ""; - if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) { - throw new phpmailerException($this->Lang('provide_address'), self::STOP_CRITICAL); - } - - // Set whether the message is multipart/alternative - if(!empty($this->AltBody)) { - $this->ContentType = 'multipart/alternative'; - } - - $this->error_count = 0; // reset errors - $this->SetMessageType(); - //Refuse to send an empty message unless we are specifically allowing it - if (!$this->AllowEmpty and empty($this->Body)) { - throw new phpmailerException($this->Lang('empty_message'), self::STOP_CRITICAL); - } - - $this->MIMEHeader = $this->CreateHeader(); - $this->MIMEBody = $this->CreateBody(); - - // To capture the complete message when using mail(), create - // an extra header list which CreateHeader() doesn't fold in - if ($this->Mailer == 'mail') { - if (count($this->to) > 0) { - $this->mailHeader .= $this->AddrAppend("To", $this->to); - } else { - $this->mailHeader .= $this->HeaderLine("To", "undisclosed-recipients:;"); - } - $this->mailHeader .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader(trim($this->Subject)))); - } - - // digitally sign with DKIM if enabled - if (!empty($this->DKIM_domain) && !empty($this->DKIM_private) && !empty($this->DKIM_selector) && !empty($this->DKIM_domain) && file_exists($this->DKIM_private)) { - $header_dkim = $this->DKIM_Add($this->MIMEHeader . $this->mailHeader, $this->EncodeHeader($this->SecureHeader($this->Subject)), $this->MIMEBody); - $this->MIMEHeader = str_replace("\r\n", "\n", $header_dkim) . $this->MIMEHeader; - } - - return true; - - } catch (phpmailerException $e) { - $this->SetError($e->getMessage()); - if ($this->exceptions) { - throw $e; - } - return false; - } - } - - /** - * Actual Email transport function - * Send the email via the selected mechanism - * @throws phpmailerException - * @return bool - */ - public function PostSend() { - try { - // Choose the mailer and send through it - switch($this->Mailer) { - case 'sendmail': - return $this->SendmailSend($this->MIMEHeader, $this->MIMEBody); - case 'smtp': - return $this->SmtpSend($this->MIMEHeader, $this->MIMEBody); - case 'mail': - return $this->MailSend($this->MIMEHeader, $this->MIMEBody); - default: - return $this->MailSend($this->MIMEHeader, $this->MIMEBody); - } - } catch (phpmailerException $e) { - $this->SetError($e->getMessage()); - if ($this->exceptions) { - throw $e; - } - if ($this->SMTPDebug) { - $this->edebug($e->getMessage()."\n"); - } - } - return false; - } - - /** - * Sends mail using the $Sendmail program. - * @param string $header The message headers - * @param string $body The message body - * @throws phpmailerException - * @access protected - * @return bool - */ - protected function SendmailSend($header, $body) { - if ($this->Sender != '') { - $sendmail = sprintf("%s -oi -f%s -t", escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender)); - } else { - $sendmail = sprintf("%s -oi -t", escapeshellcmd($this->Sendmail)); - } - if ($this->SingleTo === true) { - foreach ($this->SingleToArray as $val) { - if(!@$mail = popen($sendmail, 'w')) { - throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL); - } - fputs($mail, "To: " . $val . "\n"); - fputs($mail, $header); - fputs($mail, $body); - $result = pclose($mail); - // implement call back function if it exists - $isSent = ($result == 0) ? 1 : 0; - $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body); - if($result != 0) { - throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL); - } - } - } else { - if(!@$mail = popen($sendmail, 'w')) { - throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL); - } - fputs($mail, $header); - fputs($mail, $body); - $result = pclose($mail); - // implement call back function if it exists - $isSent = ($result == 0) ? 1 : 0; - $this->doCallback($isSent, $this->to, $this->cc, $this->bcc, $this->Subject, $body); - if($result != 0) { - throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL); - } - } - return true; - } - - /** - * Sends mail using the PHP mail() function. - * @param string $header The message headers - * @param string $body The message body - * @throws phpmailerException - * @access protected - * @return bool - */ - protected function MailSend($header, $body) { - $toArr = array(); - foreach($this->to as $t) { - $toArr[] = $this->AddrFormat($t); - } - $to = implode(', ', $toArr); - - if (empty($this->Sender)) { - $params = " "; - } else { - $params = sprintf("-f%s", $this->Sender); - } - if ($this->Sender != '' and !ini_get('safe_mode')) { - $old_from = ini_get('sendmail_from'); - ini_set('sendmail_from', $this->Sender); - } - $rt = false; - if ($this->SingleTo === true && count($toArr) > 1) { - foreach ($toArr as $val) { - $rt = $this->mail_passthru($val, $this->Subject, $body, $header, $params); - // implement call back function if it exists - $isSent = ($rt == 1) ? 1 : 0; - $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body); - } - } else { - $rt = $this->mail_passthru($to, $this->Subject, $body, $header, $params); - // implement call back function if it exists - $isSent = ($rt == 1) ? 1 : 0; - $this->doCallback($isSent, $to, $this->cc, $this->bcc, $this->Subject, $body); - } - if (isset($old_from)) { - ini_set('sendmail_from', $old_from); - } - if(!$rt) { - throw new phpmailerException($this->Lang('instantiate'), self::STOP_CRITICAL); - } - return true; - } - - /** - * Sends mail via SMTP using PhpSMTP - * Returns false if there is a bad MAIL FROM, RCPT, or DATA input. - * @param string $header The message headers - * @param string $body The message body - * @throws phpmailerException - * @uses SMTP - * @access protected - * @return bool - */ - protected function SmtpSend($header, $body) { - require_once $this->PluginDir . 'class.smtp.php'; - $bad_rcpt = array(); - - if(!$this->SmtpConnect()) { - throw new phpmailerException($this->Lang('smtp_connect_failed'), self::STOP_CRITICAL); - } - $smtp_from = ($this->Sender == '') ? $this->From : $this->Sender; - if(!$this->smtp->Mail($smtp_from)) { - $this->SetError($this->Lang('from_failed') . $smtp_from . ' : ' .implode(',', $this->smtp->getError())); - throw new phpmailerException($this->ErrorInfo, self::STOP_CRITICAL); - } - - // Attempt to send attach all recipients - foreach($this->to as $to) { - if (!$this->smtp->Recipient($to[0])) { - $bad_rcpt[] = $to[0]; - // implement call back function if it exists - $isSent = 0; - $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body); - } else { - // implement call back function if it exists - $isSent = 1; - $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body); - } - } - foreach($this->cc as $cc) { - if (!$this->smtp->Recipient($cc[0])) { - $bad_rcpt[] = $cc[0]; - // implement call back function if it exists - $isSent = 0; - $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body); - } else { - // implement call back function if it exists - $isSent = 1; - $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body); - } - } - foreach($this->bcc as $bcc) { - if (!$this->smtp->Recipient($bcc[0])) { - $bad_rcpt[] = $bcc[0]; - // implement call back function if it exists - $isSent = 0; - $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body); - } else { - // implement call back function if it exists - $isSent = 1; - $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body); - } - } - - - if (count($bad_rcpt) > 0 ) { //Create error message for any bad addresses - $badaddresses = implode(', ', $bad_rcpt); - throw new phpmailerException($this->Lang('recipients_failed') . $badaddresses); - } - if(!$this->smtp->Data($header . $body)) { - throw new phpmailerException($this->Lang('data_not_accepted'), self::STOP_CRITICAL); - } - if($this->SMTPKeepAlive == true) { - $this->smtp->Reset(); - } else { - $this->smtp->Quit(); - $this->smtp->Close(); - } - return true; - } - - /** - * Initiates a connection to an SMTP server. - * Returns false if the operation failed. - * @uses SMTP - * @access public - * @throws phpmailerException - * @return bool - */ - public function SmtpConnect() { - if(is_null($this->smtp)) { - $this->smtp = new SMTP; - } - - $this->smtp->Timeout = $this->Timeout; - $this->smtp->do_debug = $this->SMTPDebug; - $hosts = explode(';', $this->Host); - $index = 0; - $connection = $this->smtp->Connected(); - - // Retry while there is no connection - try { - while($index < count($hosts) && !$connection) { - $hostinfo = array(); - if (preg_match('/^(.+):([0-9]+)$/', $hosts[$index], $hostinfo)) { - $host = $hostinfo[1]; - $port = $hostinfo[2]; - } else { - $host = $hosts[$index]; - $port = $this->Port; - } - - $tls = ($this->SMTPSecure == 'tls'); - $ssl = ($this->SMTPSecure == 'ssl'); - - if ($this->smtp->Connect(($ssl ? 'ssl://':'').$host, $port, $this->Timeout)) { - - $hello = ($this->Helo != '' ? $this->Helo : $this->ServerHostname()); - $this->smtp->Hello($hello); - - if ($tls) { - if (!$this->smtp->StartTLS()) { - throw new phpmailerException($this->Lang('connect_host')); - } - - //We must resend HELO after tls negotiation - $this->smtp->Hello($hello); - } - - $connection = true; - if ($this->SMTPAuth) { - if (!$this->smtp->Authenticate($this->Username, $this->Password, $this->AuthType, $this->Realm, $this->Workstation)) { - throw new phpmailerException($this->Lang('authenticate')); - } - } - } - $index++; - if (!$connection) { - throw new phpmailerException($this->Lang('connect_host')); - } - } - } catch (phpmailerException $e) { - $this->smtp->Reset(); - if ($this->exceptions) { - throw $e; - } - } - return true; - } - - /** - * Closes the active SMTP session if one exists. - * @return void - */ - public function SmtpClose() { - if ($this->smtp !== null) { - if($this->smtp->Connected()) { - $this->smtp->Quit(); - $this->smtp->Close(); - } - } - } - - /** - * Sets the language for all class error messages. - * Returns false if it cannot load the language file. The default language is English. - * @param string $langcode ISO 639-1 2-character language code (e.g. Portuguese: "br") - * @param string $lang_path Path to the language file directory - * @return bool - * @access public - */ - function SetLanguage($langcode = 'en', $lang_path = 'language/') { - //Define full set of translatable strings - $PHPMAILER_LANG = array( - 'authenticate' => 'SMTP Error: Could not authenticate.', - 'connect_host' => 'SMTP Error: Could not connect to SMTP host.', - 'data_not_accepted' => 'SMTP Error: Data not accepted.', - 'empty_message' => 'Message body empty', - 'encoding' => 'Unknown encoding: ', - 'execute' => 'Could not execute: ', - 'file_access' => 'Could not access file: ', - 'file_open' => 'File Error: Could not open file: ', - 'from_failed' => 'The following From address failed: ', - 'instantiate' => 'Could not instantiate mail function.', - 'invalid_address' => 'Invalid address', - 'mailer_not_supported' => ' mailer is not supported.', - 'provide_address' => 'You must provide at least one recipient email address.', - 'recipients_failed' => 'SMTP Error: The following recipients failed: ', - 'signing' => 'Signing Error: ', - 'smtp_connect_failed' => 'SMTP Connect() failed.', - 'smtp_error' => 'SMTP server error: ', - 'variable_set' => 'Cannot set or reset variable: ' - ); - //Overwrite language-specific strings. This way we'll never have missing translations - no more "language string failed to load"! - $l = true; - if ($langcode != 'en') { //There is no English translation file - $l = @include $lang_path.'phpmailer.lang-'.$langcode.'.php'; - } - $this->language = $PHPMAILER_LANG; - return ($l == true); //Returns false if language not found - } - - /** - * Return the current array of language strings - * @return array - */ - public function GetTranslations() { - return $this->language; - } - - ///////////////////////////////////////////////// - // METHODS, MESSAGE CREATION - ///////////////////////////////////////////////// - - /** - * Creates recipient headers. - * @access public - * @param string $type - * @param array $addr - * @return string - */ - public function AddrAppend($type, $addr) { - $addr_str = $type . ': '; - $addresses = array(); - foreach ($addr as $a) { - $addresses[] = $this->AddrFormat($a); - } - $addr_str .= implode(', ', $addresses); - $addr_str .= $this->LE; - - return $addr_str; - } - - /** - * Formats an address correctly. - * @access public - * @param string $addr - * @return string - */ - public function AddrFormat($addr) { - if (empty($addr[1])) { - return $this->SecureHeader($addr[0]); - } else { - return $this->EncodeHeader($this->SecureHeader($addr[1]), 'phrase') . " <" . $this->SecureHeader($addr[0]) . ">"; - } - } - - /** - * Wraps message for use with mailers that do not - * automatically perform wrapping and for quoted-printable. - * Original written by philippe. - * @param string $message The message to wrap - * @param integer $length The line length to wrap to - * @param boolean $qp_mode Whether to run in Quoted-Printable mode - * @access public - * @return string - */ - public function WrapText($message, $length, $qp_mode = false) { - $soft_break = ($qp_mode) ? sprintf(" =%s", $this->LE) : $this->LE; - // If utf-8 encoding is used, we will need to make sure we don't - // split multibyte characters when we wrap - $is_utf8 = (strtolower($this->CharSet) == "utf-8"); - $lelen = strlen($this->LE); - $crlflen = strlen(self::CRLF); - - $message = $this->FixEOL($message); - if (substr($message, -$lelen) == $this->LE) { - $message = substr($message, 0, -$lelen); - } - - $line = explode($this->LE, $message); // Magic. We know FixEOL uses $LE - $message = ''; - for ($i = 0 ;$i < count($line); $i++) { - $line_part = explode(' ', $line[$i]); - $buf = ''; - for ($e = 0; $e $length)) { - $space_left = $length - strlen($buf) - $crlflen; - if ($e != 0) { - if ($space_left > 20) { - $len = $space_left; - if ($is_utf8) { - $len = $this->UTF8CharBoundary($word, $len); - } elseif (substr($word, $len - 1, 1) == "=") { - $len--; - } elseif (substr($word, $len - 2, 1) == "=") { - $len -= 2; - } - $part = substr($word, 0, $len); - $word = substr($word, $len); - $buf .= ' ' . $part; - $message .= $buf . sprintf("=%s", self::CRLF); - } else { - $message .= $buf . $soft_break; - } - $buf = ''; - } - while (strlen($word) > 0) { - if ($length <= 0) { - break; - } - $len = $length; - if ($is_utf8) { - $len = $this->UTF8CharBoundary($word, $len); - } elseif (substr($word, $len - 1, 1) == "=") { - $len--; - } elseif (substr($word, $len - 2, 1) == "=") { - $len -= 2; - } - $part = substr($word, 0, $len); - $word = substr($word, $len); - - if (strlen($word) > 0) { - $message .= $part . sprintf("=%s", self::CRLF); - } else { - $buf = $part; - } - } - } else { - $buf_o = $buf; - $buf .= ($e == 0) ? $word : (' ' . $word); - - if (strlen($buf) > $length and $buf_o != '') { - $message .= $buf_o . $soft_break; - $buf = $word; - } - } - } - $message .= $buf . self::CRLF; - } - - return $message; - } - - /** - * Finds last character boundary prior to maxLength in a utf-8 - * quoted (printable) encoded string. - * Original written by Colin Brown. - * @access public - * @param string $encodedText utf-8 QP text - * @param int $maxLength find last character boundary prior to this length - * @return int - */ - public function UTF8CharBoundary($encodedText, $maxLength) { - $foundSplitPos = false; - $lookBack = 3; - while (!$foundSplitPos) { - $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack); - $encodedCharPos = strpos($lastChunk, "="); - if ($encodedCharPos !== false) { - // Found start of encoded character byte within $lookBack block. - // Check the encoded byte value (the 2 chars after the '=') - $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2); - $dec = hexdec($hex); - if ($dec < 128) { // Single byte character. - // If the encoded char was found at pos 0, it will fit - // otherwise reduce maxLength to start of the encoded char - $maxLength = ($encodedCharPos == 0) ? $maxLength : - $maxLength - ($lookBack - $encodedCharPos); - $foundSplitPos = true; - } elseif ($dec >= 192) { // First byte of a multi byte character - // Reduce maxLength to split at start of character - $maxLength = $maxLength - ($lookBack - $encodedCharPos); - $foundSplitPos = true; - } elseif ($dec < 192) { // Middle byte of a multi byte character, look further back - $lookBack += 3; - } - } else { - // No encoded character found - $foundSplitPos = true; - } - } - return $maxLength; - } - - - /** - * Set the body wrapping. - * @access public - * @return void - */ - public function SetWordWrap() { - if($this->WordWrap < 1) { - return; - } - - switch($this->message_type) { - case 'alt': - case 'alt_inline': - case 'alt_attach': - case 'alt_inline_attach': - $this->AltBody = $this->WrapText($this->AltBody, $this->WordWrap); - break; - default: - $this->Body = $this->WrapText($this->Body, $this->WordWrap); - break; - } - } - - /** - * Assembles message header. - * @access public - * @return string The assembled header - */ - public function CreateHeader() { - $result = ''; - - // Set the boundaries - $uniq_id = md5(uniqid(time())); - $this->boundary[1] = 'b1_' . $uniq_id; - $this->boundary[2] = 'b2_' . $uniq_id; - $this->boundary[3] = 'b3_' . $uniq_id; - - if ($this->MessageDate == '') { - $result .= $this->HeaderLine('Date', self::RFCDate()); - } else { - $result .= $this->HeaderLine('Date', $this->MessageDate); - } - - if ($this->ReturnPath) { - $result .= $this->HeaderLine('Return-Path', '<'.trim($this->ReturnPath).'>'); - } elseif ($this->Sender == '') { - $result .= $this->HeaderLine('Return-Path', '<'.trim($this->From).'>'); - } else { - $result .= $this->HeaderLine('Return-Path', '<'.trim($this->Sender).'>'); - } - - // To be created automatically by mail() - if($this->Mailer != 'mail') { - if ($this->SingleTo === true) { - foreach($this->to as $t) { - $this->SingleToArray[] = $this->AddrFormat($t); - } - } else { - if(count($this->to) > 0) { - $result .= $this->AddrAppend('To', $this->to); - } elseif (count($this->cc) == 0) { - $result .= $this->HeaderLine('To', 'undisclosed-recipients:;'); - } - } - } - - $from = array(); - $from[0][0] = trim($this->From); - $from[0][1] = $this->FromName; - $result .= $this->AddrAppend('From', $from); - - // sendmail and mail() extract Cc from the header before sending - if(count($this->cc) > 0) { - $result .= $this->AddrAppend('Cc', $this->cc); - } - - // sendmail and mail() extract Bcc from the header before sending - if((($this->Mailer == 'sendmail') || ($this->Mailer == 'mail')) && (count($this->bcc) > 0)) { - $result .= $this->AddrAppend('Bcc', $this->bcc); - } - - if(count($this->ReplyTo) > 0) { - $result .= $this->AddrAppend('Reply-To', $this->ReplyTo); - } - - // mail() sets the subject itself - if($this->Mailer != 'mail') { - $result .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader($this->Subject))); - } - - if($this->MessageID != '') { - $result .= $this->HeaderLine('Message-ID', $this->MessageID); - } else { - $result .= sprintf("Message-ID: <%s@%s>%s", $uniq_id, $this->ServerHostname(), $this->LE); - } - $result .= $this->HeaderLine('X-Priority', $this->Priority); - if ($this->XMailer == '') { - $result .= $this->HeaderLine('X-Mailer', 'PHPMailer '.$this->Version.' (https://github.com/PHPMailer/PHPMailer/)'); - } else { - $myXmailer = trim($this->XMailer); - if ($myXmailer) { - $result .= $this->HeaderLine('X-Mailer', $myXmailer); - } - } - - if($this->ConfirmReadingTo != '') { - $result .= $this->HeaderLine('Disposition-Notification-To', '<' . trim($this->ConfirmReadingTo) . '>'); - } - - // Add custom headers - for($index = 0; $index < count($this->CustomHeader); $index++) { - $result .= $this->HeaderLine(trim($this->CustomHeader[$index][0]), $this->EncodeHeader(trim($this->CustomHeader[$index][1]))); - } - if (!$this->sign_key_file) { - $result .= $this->HeaderLine('MIME-Version', '1.0'); - $result .= $this->GetMailMIME(); - } - - return $result; - } - - /** - * Returns the message MIME. - * @access public - * @return string - */ - public function GetMailMIME() { - $result = ''; - switch($this->message_type) { - case 'inline': - $result .= $this->HeaderLine('Content-Type', 'multipart/related;'); - $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"'); - break; - case 'attach': - case 'inline_attach': - case 'alt_attach': - case 'alt_inline_attach': - $result .= $this->HeaderLine('Content-Type', 'multipart/mixed;'); - $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"'); - break; - case 'alt': - case 'alt_inline': - $result .= $this->HeaderLine('Content-Type', 'multipart/alternative;'); - $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"'); - break; - default: - // Catches case 'plain': and case '': - $result .= $this->HeaderLine('Content-Transfer-Encoding', $this->Encoding); - $result .= $this->TextLine('Content-Type: '.$this->ContentType.'; charset='.$this->CharSet); - break; - } - - if($this->Mailer != 'mail') { - $result .= $this->LE; - } - - return $result; - } - - /** - * Returns the MIME message (headers and body). Only really valid post PreSend(). - * @access public - * @return string - */ - public function GetSentMIMEMessage() { - return $this->MIMEHeader . $this->mailHeader . self::CRLF . $this->MIMEBody; - } - - - /** - * Assembles the message body. Returns an empty string on failure. - * @access public - * @throws phpmailerException - * @return string The assembled message body - */ - public function CreateBody() { - $body = ''; - - if ($this->sign_key_file) { - $body .= $this->GetMailMIME().$this->LE; - } - - $this->SetWordWrap(); - - switch($this->message_type) { - case 'inline': - $body .= $this->GetBoundary($this->boundary[1], '', '', ''); - $body .= $this->EncodeString($this->Body, $this->Encoding); - $body .= $this->LE.$this->LE; - $body .= $this->AttachAll('inline', $this->boundary[1]); - break; - case 'attach': - $body .= $this->GetBoundary($this->boundary[1], '', '', ''); - $body .= $this->EncodeString($this->Body, $this->Encoding); - $body .= $this->LE.$this->LE; - $body .= $this->AttachAll('attachment', $this->boundary[1]); - break; - case 'inline_attach': - $body .= $this->TextLine('--' . $this->boundary[1]); - $body .= $this->HeaderLine('Content-Type', 'multipart/related;'); - $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"'); - $body .= $this->LE; - $body .= $this->GetBoundary($this->boundary[2], '', '', ''); - $body .= $this->EncodeString($this->Body, $this->Encoding); - $body .= $this->LE.$this->LE; - $body .= $this->AttachAll('inline', $this->boundary[2]); - $body .= $this->LE; - $body .= $this->AttachAll('attachment', $this->boundary[1]); - break; - case 'alt': - $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', ''); - $body .= $this->EncodeString($this->AltBody, $this->Encoding); - $body .= $this->LE.$this->LE; - $body .= $this->GetBoundary($this->boundary[1], '', 'text/html', ''); - $body .= $this->EncodeString($this->Body, $this->Encoding); - $body .= $this->LE.$this->LE; - $body .= $this->EndBoundary($this->boundary[1]); - break; - case 'alt_inline': - $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', ''); - $body .= $this->EncodeString($this->AltBody, $this->Encoding); - $body .= $this->LE.$this->LE; - $body .= $this->TextLine('--' . $this->boundary[1]); - $body .= $this->HeaderLine('Content-Type', 'multipart/related;'); - $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"'); - $body .= $this->LE; - $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', ''); - $body .= $this->EncodeString($this->Body, $this->Encoding); - $body .= $this->LE.$this->LE; - $body .= $this->AttachAll('inline', $this->boundary[2]); - $body .= $this->LE; - $body .= $this->EndBoundary($this->boundary[1]); - break; - case 'alt_attach': - $body .= $this->TextLine('--' . $this->boundary[1]); - $body .= $this->HeaderLine('Content-Type', 'multipart/alternative;'); - $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"'); - $body .= $this->LE; - $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', ''); - $body .= $this->EncodeString($this->AltBody, $this->Encoding); - $body .= $this->LE.$this->LE; - $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', ''); - $body .= $this->EncodeString($this->Body, $this->Encoding); - $body .= $this->LE.$this->LE; - $body .= $this->EndBoundary($this->boundary[2]); - $body .= $this->LE; - $body .= $this->AttachAll('attachment', $this->boundary[1]); - break; - case 'alt_inline_attach': - $body .= $this->TextLine('--' . $this->boundary[1]); - $body .= $this->HeaderLine('Content-Type', 'multipart/alternative;'); - $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"'); - $body .= $this->LE; - $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', ''); - $body .= $this->EncodeString($this->AltBody, $this->Encoding); - $body .= $this->LE.$this->LE; - $body .= $this->TextLine('--' . $this->boundary[2]); - $body .= $this->HeaderLine('Content-Type', 'multipart/related;'); - $body .= $this->TextLine("\tboundary=\"" . $this->boundary[3] . '"'); - $body .= $this->LE; - $body .= $this->GetBoundary($this->boundary[3], '', 'text/html', ''); - $body .= $this->EncodeString($this->Body, $this->Encoding); - $body .= $this->LE.$this->LE; - $body .= $this->AttachAll('inline', $this->boundary[3]); - $body .= $this->LE; - $body .= $this->EndBoundary($this->boundary[2]); - $body .= $this->LE; - $body .= $this->AttachAll('attachment', $this->boundary[1]); - break; - default: - // catch case 'plain' and case '' - $body .= $this->EncodeString($this->Body, $this->Encoding); - break; - } - - if ($this->IsError()) { - $body = ''; - } elseif ($this->sign_key_file) { - try { - if (!defined('PKCS7_TEXT')) { - throw new phpmailerException($this->Lang('signing').' OpenSSL extension missing.'); - } - $file = tempnam(sys_get_temp_dir(), 'mail'); - file_put_contents($file, $body); //TODO check this worked - $signed = tempnam(sys_get_temp_dir(), 'signed'); - if (@openssl_pkcs7_sign($file, $signed, 'file://'.realpath($this->sign_cert_file), array('file://'.realpath($this->sign_key_file), $this->sign_key_pass), null)) { - @unlink($file); - $body = file_get_contents($signed); - @unlink($signed); - } else { - @unlink($file); - @unlink($signed); - throw new phpmailerException($this->Lang('signing').openssl_error_string()); - } - } catch (phpmailerException $e) { - $body = ''; - if ($this->exceptions) { - throw $e; - } - } - } - return $body; - } - - /** - * Returns the start of a message boundary. - * @access protected - * @param string $boundary - * @param string $charSet - * @param string $contentType - * @param string $encoding - * @return string - */ - protected function GetBoundary($boundary, $charSet, $contentType, $encoding) { - $result = ''; - if($charSet == '') { - $charSet = $this->CharSet; - } - if($contentType == '') { - $contentType = $this->ContentType; - } - if($encoding == '') { - $encoding = $this->Encoding; - } - $result .= $this->TextLine('--' . $boundary); - $result .= sprintf("Content-Type: %s; charset=%s", $contentType, $charSet); - $result .= $this->LE; - $result .= $this->HeaderLine('Content-Transfer-Encoding', $encoding); - $result .= $this->LE; - - return $result; - } - - /** - * Returns the end of a message boundary. - * @access protected - * @param string $boundary - * @return string - */ - protected function EndBoundary($boundary) { - return $this->LE . '--' . $boundary . '--' . $this->LE; - } - - /** - * Sets the message type. - * @access protected - * @return void - */ - protected function SetMessageType() { - $this->message_type = array(); - if($this->AlternativeExists()) $this->message_type[] = "alt"; - if($this->InlineImageExists()) $this->message_type[] = "inline"; - if($this->AttachmentExists()) $this->message_type[] = "attach"; - $this->message_type = implode("_", $this->message_type); - if($this->message_type == "") $this->message_type = "plain"; - } - - /** - * Returns a formatted header line. - * @access public - * @param string $name - * @param string $value - * @return string - */ - public function HeaderLine($name, $value) { - return $name . ': ' . $value . $this->LE; - } - - /** - * Returns a formatted mail line. - * @access public - * @param string $value - * @return string - */ - public function TextLine($value) { - return $value . $this->LE; - } - - ///////////////////////////////////////////////// - // CLASS METHODS, ATTACHMENTS - ///////////////////////////////////////////////// - - /** - * Adds an attachment from a path on the filesystem. - * Returns false if the file could not be found - * or accessed. - * @param string $path Path to the attachment. - * @param string $name Overrides the attachment name. - * @param string $encoding File encoding (see $Encoding). - * @param string $type File extension (MIME) type. - * @throws phpmailerException - * @return bool - */ - public function AddAttachment($path, $name = '', $encoding = 'base64', $type = 'application/octet-stream') { - try { - if ( !@is_file($path) ) { - throw new phpmailerException($this->Lang('file_access') . $path, self::STOP_CONTINUE); - } - $filename = basename($path); - if ( $name == '' ) { - $name = $filename; - } - - $this->attachment[] = array( - 0 => $path, - 1 => $filename, - 2 => $name, - 3 => $encoding, - 4 => $type, - 5 => false, // isStringAttachment - 6 => 'attachment', - 7 => 0 - ); - - } catch (phpmailerException $e) { - $this->SetError($e->getMessage()); - if ($this->exceptions) { - throw $e; - } - if ($this->SMTPDebug) { - $this->edebug($e->getMessage()."\n"); - } - if ( $e->getCode() == self::STOP_CRITICAL ) { - return false; - } - } - return true; - } - - /** - * Return the current array of attachments - * @return array - */ - public function GetAttachments() { - return $this->attachment; - } - - /** - * Attaches all fs, string, and binary attachments to the message. - * Returns an empty string on failure. - * @access protected - * @param string $disposition_type - * @param string $boundary - * @return string - */ - protected function AttachAll($disposition_type, $boundary) { - // Return text of body - $mime = array(); - $cidUniq = array(); - $incl = array(); - - // Add all attachments - foreach ($this->attachment as $attachment) { - // CHECK IF IT IS A VALID DISPOSITION_FILTER - if($attachment[6] == $disposition_type) { - // Check for string attachment - $string = ''; - $path = ''; - $bString = $attachment[5]; - if ($bString) { - $string = $attachment[0]; - } else { - $path = $attachment[0]; - } - - $inclhash = md5(serialize($attachment)); - if (in_array($inclhash, $incl)) { continue; } - $incl[] = $inclhash; - $filename = $attachment[1]; - $name = $attachment[2]; - $encoding = $attachment[3]; - $type = $attachment[4]; - $disposition = $attachment[6]; - $cid = $attachment[7]; - if ( $disposition == 'inline' && isset($cidUniq[$cid]) ) { continue; } - $cidUniq[$cid] = true; - - $mime[] = sprintf("--%s%s", $boundary, $this->LE); - $mime[] = sprintf("Content-Type: %s; name=\"%s\"%s", $type, $this->EncodeHeader($this->SecureHeader($name)), $this->LE); - $mime[] = sprintf("Content-Transfer-Encoding: %s%s", $encoding, $this->LE); - - if($disposition == 'inline') { - $mime[] = sprintf("Content-ID: <%s>%s", $cid, $this->LE); - } - - $mime[] = sprintf("Content-Disposition: %s; filename=\"%s\"%s", $disposition, $this->EncodeHeader($this->SecureHeader($name)), $this->LE.$this->LE); - - // Encode as string attachment - if($bString) { - $mime[] = $this->EncodeString($string, $encoding); - if($this->IsError()) { - return ''; - } - $mime[] = $this->LE.$this->LE; - } else { - $mime[] = $this->EncodeFile($path, $encoding); - if($this->IsError()) { - return ''; - } - $mime[] = $this->LE.$this->LE; - } - } - } - - $mime[] = sprintf("--%s--%s", $boundary, $this->LE); - - return implode("", $mime); - } - - /** - * Encodes attachment in requested format. - * Returns an empty string on failure. - * @param string $path The full path to the file - * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable' - * @throws phpmailerException - * @see EncodeFile() - * @access protected - * @return string - */ - protected function EncodeFile($path, $encoding = 'base64') { - try { - if (!is_readable($path)) { - throw new phpmailerException($this->Lang('file_open') . $path, self::STOP_CONTINUE); - } - $magic_quotes = get_magic_quotes_runtime(); - if ($magic_quotes) { - if (version_compare(PHP_VERSION, '5.3.0', '<')) { - set_magic_quotes_runtime(0); - } else { - ini_set('magic_quotes_runtime', 0); - } - } - $file_buffer = file_get_contents($path); - $file_buffer = $this->EncodeString($file_buffer, $encoding); - if ($magic_quotes) { - if (version_compare(PHP_VERSION, '5.3.0', '<')) { - set_magic_quotes_runtime($magic_quotes); - } else { - ini_set('magic_quotes_runtime', $magic_quotes); - } - } - return $file_buffer; - } catch (Exception $e) { - $this->SetError($e->getMessage()); - return ''; - } - } - - /** - * Encodes string to requested format. - * Returns an empty string on failure. - * @param string $str The text to encode - * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable' - * @access public - * @return string - */ - public function EncodeString($str, $encoding = 'base64') { - $encoded = ''; - switch(strtolower($encoding)) { - case 'base64': - $encoded = chunk_split(base64_encode($str), 76, $this->LE); - break; - case '7bit': - case '8bit': - $encoded = $this->FixEOL($str); - //Make sure it ends with a line break - if (substr($encoded, -(strlen($this->LE))) != $this->LE) - $encoded .= $this->LE; - break; - case 'binary': - $encoded = $str; - break; - case 'quoted-printable': - $encoded = $this->EncodeQP($str); - break; - default: - $this->SetError($this->Lang('encoding') . $encoding); - break; - } - return $encoded; - } - - /** - * Encode a header string to best (shortest) of Q, B, quoted or none. - * @access public - * @param string $str - * @param string $position - * @return string - */ - public function EncodeHeader($str, $position = 'text') { - $x = 0; - - switch (strtolower($position)) { - case 'phrase': - if (!preg_match('/[\200-\377]/', $str)) { - // Can't use addslashes as we don't know what value has magic_quotes_sybase - $encoded = addcslashes($str, "\0..\37\177\\\""); - if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) { - return ($encoded); - } else { - return ("\"$encoded\""); - } - } - $x = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches); - break; - case 'comment': - $x = preg_match_all('/[()"]/', $str, $matches); - // Fall-through - case 'text': - default: - $x += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches); - break; - } - - if ($x == 0) { //There are no chars that need encoding - return ($str); - } - - $maxlen = 75 - 7 - strlen($this->CharSet); - // Try to select the encoding which should produce the shortest output - if ($x > strlen($str)/3) { //More than a third of the content will need encoding, so B encoding will be most efficient - $encoding = 'B'; - if (function_exists('mb_strlen') && $this->HasMultiBytes($str)) { - // Use a custom function which correctly encodes and wraps long - // multibyte strings without breaking lines within a character - $encoded = $this->Base64EncodeWrapMB($str, "\n"); - } else { - $encoded = base64_encode($str); - $maxlen -= $maxlen % 4; - $encoded = trim(chunk_split($encoded, $maxlen, "\n")); - } - } else { - $encoding = 'Q'; - $encoded = $this->EncodeQ($str, $position); - $encoded = $this->WrapText($encoded, $maxlen, true); - $encoded = str_replace('='.self::CRLF, "\n", trim($encoded)); - } - - $encoded = preg_replace('/^(.*)$/m', " =?".$this->CharSet."?$encoding?\\1?=", $encoded); - $encoded = trim(str_replace("\n", $this->LE, $encoded)); - - return $encoded; - } - - /** - * Checks if a string contains multibyte characters. - * @access public - * @param string $str multi-byte text to wrap encode - * @return bool - */ - public function HasMultiBytes($str) { - if (function_exists('mb_strlen')) { - return (strlen($str) > mb_strlen($str, $this->CharSet)); - } else { // Assume no multibytes (we can't handle without mbstring functions anyway) - return false; - } - } - - /** - * Correctly encodes and wraps long multibyte strings for mail headers - * without breaking lines within a character. - * Adapted from a function by paravoid at http://uk.php.net/manual/en/function.mb-encode-mimeheader.php - * @access public - * @param string $str multi-byte text to wrap encode - * @param string $lf string to use as linefeed/end-of-line - * @return string - */ - public function Base64EncodeWrapMB($str, $lf=null) { - $start = "=?".$this->CharSet."?B?"; - $end = "?="; - $encoded = ""; - if ($lf === null) { - $lf = $this->LE; - } - - $mb_length = mb_strlen($str, $this->CharSet); - // Each line must have length <= 75, including $start and $end - $length = 75 - strlen($start) - strlen($end); - // Average multi-byte ratio - $ratio = $mb_length / strlen($str); - // Base64 has a 4:3 ratio - $offset = $avgLength = floor($length * $ratio * .75); - - for ($i = 0; $i < $mb_length; $i += $offset) { - $lookBack = 0; - - do { - $offset = $avgLength - $lookBack; - $chunk = mb_substr($str, $i, $offset, $this->CharSet); - $chunk = base64_encode($chunk); - $lookBack++; - } - while (strlen($chunk) > $length); - - $encoded .= $chunk . $lf; - } - - // Chomp the last linefeed - $encoded = substr($encoded, 0, -strlen($lf)); - return $encoded; - } - - /** - * Encode string to RFC2045 (6.7) quoted-printable format - * @access public - * @param string $string The text to encode - * @param integer $line_max Number of chars allowed on a line before wrapping - * @return string - * @link PHP version adapted from http://www.php.net/manual/en/function.quoted-printable-decode.php#89417 - */ - public function EncodeQP($string, $line_max = 76) { - if (function_exists('quoted_printable_encode')) { //Use native function if it's available (>= PHP5.3) - return quoted_printable_encode($string); - } - //Fall back to a pure PHP implementation - $string = str_replace(array('%20', '%0D%0A.', '%0D%0A', '%'), array(' ', "\r\n=2E", "\r\n", '='), rawurlencode($string)); - $string = preg_replace('/[^\r\n]{'.($line_max - 3).'}[^=\r\n]{2}/', "$0=\r\n", $string); - return $string; - } - - /** - * Wrapper to preserve BC for old QP encoding function that was removed - * @see EncodeQP() - * @access public - * @param string $string - * @param integer $line_max - * @param bool $space_conv - * @return string - */ - public function EncodeQPphp($string, $line_max = 76, $space_conv = false) { - return $this->EncodeQP($string, $line_max); - } - - /** - * Encode string to q encoding. - * @link http://tools.ietf.org/html/rfc2047 - * @param string $str the text to encode - * @param string $position Where the text is going to be used, see the RFC for what that means - * @access public - * @return string - */ - public function EncodeQ($str, $position = 'text') { - //There should not be any EOL in the string - $pattern=""; - $encoded = str_replace(array("\r", "\n"), '', $str); - switch (strtolower($position)) { - case 'phrase': - $pattern = '^A-Za-z0-9!*+\/ -'; - break; - - case 'comment': - $pattern = '\(\)"'; - //note that we don't break here! - //for this reason we build the $pattern without including delimiters and [] - - case 'text': - default: - //Replace every high ascii, control =, ? and _ characters - //We put \075 (=) as first value to make sure it's the first one in being converted, preventing double encode - $pattern = '\075\000-\011\013\014\016-\037\077\137\177-\377' . $pattern; - break; - } - - if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) { - foreach (array_unique($matches[0]) as $char) { - $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded); - } - } - - //Replace every spaces to _ (more readable than =20) - return str_replace(' ', '_', $encoded); -} - - - /** - * Adds a string or binary attachment (non-filesystem) to the list. - * This method can be used to attach ascii or binary data, - * such as a BLOB record from a database. - * @param string $string String attachment data. - * @param string $filename Name of the attachment. - * @param string $encoding File encoding (see $Encoding). - * @param string $type File extension (MIME) type. - * @return void - */ - public function AddStringAttachment($string, $filename, $encoding = 'base64', $type = 'application/octet-stream') { - // Append to $attachment array - $this->attachment[] = array( - 0 => $string, - 1 => $filename, - 2 => basename($filename), - 3 => $encoding, - 4 => $type, - 5 => true, // isStringAttachment - 6 => 'attachment', - 7 => 0 - ); - } - - /** - * Add an embedded attachment from a file. - * This can include images, sounds, and just about any other document type. - * Be sure to set the $type to an image type for images: - * JPEG images use 'image/jpeg', GIF uses 'image/gif', PNG uses 'image/png'. - * @param string $path Path to the attachment. - * @param string $cid Content ID of the attachment; Use this to reference - * the content when using an embedded image in HTML. - * @param string $name Overrides the attachment name. - * @param string $encoding File encoding (see $Encoding). - * @param string $type File MIME type. - * @return bool True on successfully adding an attachment - */ - public function AddEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = 'application/octet-stream') { - - if ( !@is_file($path) ) { - $this->SetError($this->Lang('file_access') . $path); - return false; - } - - $filename = basename($path); - if ( $name == '' ) { - $name = $filename; - } - - // Append to $attachment array - $this->attachment[] = array( - 0 => $path, - 1 => $filename, - 2 => $name, - 3 => $encoding, - 4 => $type, - 5 => false, // isStringAttachment - 6 => 'inline', - 7 => $cid - ); - return true; - } - - - /** - * Add an embedded stringified attachment. - * This can include images, sounds, and just about any other document type. - * Be sure to set the $type to an image type for images: - * JPEG images use 'image/jpeg', GIF uses 'image/gif', PNG uses 'image/png'. - * @param string $string The attachment binary data. - * @param string $cid Content ID of the attachment; Use this to reference - * the content when using an embedded image in HTML. - * @param string $name - * @param string $encoding File encoding (see $Encoding). - * @param string $type MIME type. - * @return bool True on successfully adding an attachment - */ - public function AddStringEmbeddedImage($string, $cid, $name = '', $encoding = 'base64', $type = 'application/octet-stream') { - // Append to $attachment array - $this->attachment[] = array( - 0 => $string, - 1 => $name, - 2 => $name, - 3 => $encoding, - 4 => $type, - 5 => true, // isStringAttachment - 6 => 'inline', - 7 => $cid - ); - return true; - } - - /** - * Returns true if an inline attachment is present. - * @access public - * @return bool - */ - public function InlineImageExists() { - foreach($this->attachment as $attachment) { - if ($attachment[6] == 'inline') { - return true; - } - } - return false; - } - - /** - * Returns true if an attachment (non-inline) is present. - * @return bool - */ - public function AttachmentExists() { - foreach($this->attachment as $attachment) { - if ($attachment[6] == 'attachment') { - return true; - } - } - return false; - } - - /** - * Does this message have an alternative body set? - * @return bool - */ - public function AlternativeExists() { - return !empty($this->AltBody); - } - - ///////////////////////////////////////////////// - // CLASS METHODS, MESSAGE RESET - ///////////////////////////////////////////////// - - /** - * Clears all recipients assigned in the TO array. Returns void. - * @return void - */ - public function ClearAddresses() { - foreach($this->to as $to) { - unset($this->all_recipients[strtolower($to[0])]); - } - $this->to = array(); - } - - /** - * Clears all recipients assigned in the CC array. Returns void. - * @return void - */ - public function ClearCCs() { - foreach($this->cc as $cc) { - unset($this->all_recipients[strtolower($cc[0])]); - } - $this->cc = array(); - } - - /** - * Clears all recipients assigned in the BCC array. Returns void. - * @return void - */ - public function ClearBCCs() { - foreach($this->bcc as $bcc) { - unset($this->all_recipients[strtolower($bcc[0])]); - } - $this->bcc = array(); - } - - /** - * Clears all recipients assigned in the ReplyTo array. Returns void. - * @return void - */ - public function ClearReplyTos() { - $this->ReplyTo = array(); - } - - /** - * Clears all recipients assigned in the TO, CC and BCC - * array. Returns void. - * @return void - */ - public function ClearAllRecipients() { - $this->to = array(); - $this->cc = array(); - $this->bcc = array(); - $this->all_recipients = array(); - } - - /** - * Clears all previously set filesystem, string, and binary - * attachments. Returns void. - * @return void - */ - public function ClearAttachments() { - $this->attachment = array(); - } - - /** - * Clears all custom headers. Returns void. - * @return void - */ - public function ClearCustomHeaders() { - $this->CustomHeader = array(); - } - - ///////////////////////////////////////////////// - // CLASS METHODS, MISCELLANEOUS - ///////////////////////////////////////////////// - - /** - * Adds the error message to the error container. - * @access protected - * @param string $msg - * @return void - */ - protected function SetError($msg) { - $this->error_count++; - if ($this->Mailer == 'smtp' and !is_null($this->smtp)) { - $lasterror = $this->smtp->getError(); - if (!empty($lasterror) and array_key_exists('smtp_msg', $lasterror)) { - $msg .= '

    ' . $this->Lang('smtp_error') . $lasterror['smtp_msg'] . "

    \n"; - } - } - $this->ErrorInfo = $msg; - } - - /** - * Returns the proper RFC 822 formatted date. - * @access public - * @return string - * @static - */ - public static function RFCDate() { - //Set the time zone to whatever the default is to avoid 500 errors - //Will default to UTC if it's not set properly in php.ini - date_default_timezone_set(@date_default_timezone_get()); - return date('D, j M Y H:i:s O'); - } - - /** - * Returns the server hostname or 'localhost.localdomain' if unknown. - * @access protected - * @return string - */ - protected function ServerHostname() { - if (!empty($this->Hostname)) { - $result = $this->Hostname; - } elseif (isset($_SERVER['SERVER_NAME'])) { - $result = $_SERVER['SERVER_NAME']; - } else { - $result = 'localhost.localdomain'; - } - - return $result; - } - - /** - * Returns a message in the appropriate language. - * @access protected - * @param string $key - * @return string - */ - protected function Lang($key) { - if(count($this->language) < 1) { - $this->SetLanguage('en'); // set the default language - } - - if(isset($this->language[$key])) { - return $this->language[$key]; - } else { - return 'Language string failed to load: ' . $key; - } - } - - /** - * Returns true if an error occurred. - * @access public - * @return bool - */ - public function IsError() { - return ($this->error_count > 0); - } - - /** - * Changes every end of line from CRLF, CR or LF to $this->LE. - * @access public - * @param string $str String to FixEOL - * @return string - */ - public function FixEOL($str) { - // condense down to \n - $nstr = str_replace(array("\r\n", "\r"), "\n", $str); - // Now convert LE as needed - if ($this->LE !== "\n") { - $nstr = str_replace("\n", $this->LE, $nstr); - } - return $nstr; - } - - /** - * Adds a custom header. $name value can be overloaded to contain - * both header name and value (name:value) - * @access public - * @param string $name custom header name - * @param string $value header value - * @return void - */ - public function AddCustomHeader($name, $value=null) { - if ($value === null) { - // Value passed in as name:value - $this->CustomHeader[] = explode(':', $name, 2); - } else { - $this->CustomHeader[] = array($name, $value); - } - } - - /** - * Creates a message from an HTML string, making modifications for inline images and backgrounds - * and creates a plain-text version by converting the HTML - * Overwrites any existing values in $this->Body and $this->AltBody - * @access public - * @param string $message HTML message string - * @param string $basedir baseline directory for path - * @param bool $advanced Whether to use the advanced HTML to text converter - * @return string $message - */ - public function MsgHTML($message, $basedir = '', $advanced = false) { - preg_match_all("/(src|background)=[\"'](.*)[\"']/Ui", $message, $images); - if(isset($images[2])) { - foreach($images[2] as $i => $url) { - // do not change urls for absolute images (thanks to corvuscorax) - if (!preg_match('#^[A-z]+://#', $url)) { - $filename = basename($url); - $directory = dirname($url); - if ($directory == '.') { - $directory = ''; - } - $cid = 'cid:' . md5($url); - $ext = pathinfo($filename, PATHINFO_EXTENSION); - $mimeType = self::_mime_types($ext); - if ( strlen($basedir) > 1 && substr($basedir, -1) != '/') { $basedir .= '/'; } - if ( strlen($directory) > 1 && substr($directory, -1) != '/') { $directory .= '/'; } - if ( $this->AddEmbeddedImage($basedir.$directory.$filename, md5($url), $filename, 'base64', $mimeType) ) { - $message = preg_replace("/".$images[1][$i]."=[\"']".preg_quote($url, '/')."[\"']/Ui", $images[1][$i]."=\"".$cid."\"", $message); - } - } - } - } - $this->IsHTML(true); - $this->Body = $message; - $this->AltBody = $this->html2text($message, $advanced); - if (empty($this->AltBody)) { - $this->AltBody = 'To view this email message, open it in a program that understands HTML!' . "\n\n"; - } - return $message; - } - - /** - * Convert an HTML string into a plain text version - * @param string $html The HTML text to convert - * @param bool $advanced Should this use the more complex html2text converter or just a simple one? - * @return string - */ - public function html2text($html, $advanced = false) { - if ($advanced) { - require_once 'extras/class.html2text.php'; - $h = new html2text($html); - return $h->get_text(); - } - return html_entity_decode(trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/s', '', $html))), ENT_QUOTES, $this->CharSet); - } - - /** - * Gets the MIME type of the embedded or inline image - * @param string $ext File extension - * @access public - * @return string MIME type of ext - * @static - */ - public static function _mime_types($ext = '') { - $mimes = array( - 'xl' => 'application/excel', - 'hqx' => 'application/mac-binhex40', - 'cpt' => 'application/mac-compactpro', - 'bin' => 'application/macbinary', - 'doc' => 'application/msword', - 'word' => 'application/msword', - 'class' => 'application/octet-stream', - 'dll' => 'application/octet-stream', - 'dms' => 'application/octet-stream', - 'exe' => 'application/octet-stream', - 'lha' => 'application/octet-stream', - 'lzh' => 'application/octet-stream', - 'psd' => 'application/octet-stream', - 'sea' => 'application/octet-stream', - 'so' => 'application/octet-stream', - 'oda' => 'application/oda', - 'pdf' => 'application/pdf', - 'ai' => 'application/postscript', - 'eps' => 'application/postscript', - 'ps' => 'application/postscript', - 'smi' => 'application/smil', - 'smil' => 'application/smil', - 'mif' => 'application/vnd.mif', - 'xls' => 'application/vnd.ms-excel', - 'ppt' => 'application/vnd.ms-powerpoint', - 'wbxml' => 'application/vnd.wap.wbxml', - 'wmlc' => 'application/vnd.wap.wmlc', - 'dcr' => 'application/x-director', - 'dir' => 'application/x-director', - 'dxr' => 'application/x-director', - 'dvi' => 'application/x-dvi', - 'gtar' => 'application/x-gtar', - 'php3' => 'application/x-httpd-php', - 'php4' => 'application/x-httpd-php', - 'php' => 'application/x-httpd-php', - 'phtml' => 'application/x-httpd-php', - 'phps' => 'application/x-httpd-php-source', - 'js' => 'application/x-javascript', - 'swf' => 'application/x-shockwave-flash', - 'sit' => 'application/x-stuffit', - 'tar' => 'application/x-tar', - 'tgz' => 'application/x-tar', - 'xht' => 'application/xhtml+xml', - 'xhtml' => 'application/xhtml+xml', - 'zip' => 'application/zip', - 'mid' => 'audio/midi', - 'midi' => 'audio/midi', - 'mp2' => 'audio/mpeg', - 'mp3' => 'audio/mpeg', - 'mpga' => 'audio/mpeg', - 'aif' => 'audio/x-aiff', - 'aifc' => 'audio/x-aiff', - 'aiff' => 'audio/x-aiff', - 'ram' => 'audio/x-pn-realaudio', - 'rm' => 'audio/x-pn-realaudio', - 'rpm' => 'audio/x-pn-realaudio-plugin', - 'ra' => 'audio/x-realaudio', - 'wav' => 'audio/x-wav', - 'bmp' => 'image/bmp', - 'gif' => 'image/gif', - 'jpeg' => 'image/jpeg', - 'jpe' => 'image/jpeg', - 'jpg' => 'image/jpeg', - 'png' => 'image/png', - 'tiff' => 'image/tiff', - 'tif' => 'image/tiff', - 'eml' => 'message/rfc822', - 'css' => 'text/css', - 'html' => 'text/html', - 'htm' => 'text/html', - 'shtml' => 'text/html', - 'log' => 'text/plain', - 'text' => 'text/plain', - 'txt' => 'text/plain', - 'rtx' => 'text/richtext', - 'rtf' => 'text/rtf', - 'xml' => 'text/xml', - 'xsl' => 'text/xml', - 'mpeg' => 'video/mpeg', - 'mpe' => 'video/mpeg', - 'mpg' => 'video/mpeg', - 'mov' => 'video/quicktime', - 'qt' => 'video/quicktime', - 'rv' => 'video/vnd.rn-realvideo', - 'avi' => 'video/x-msvideo', - 'movie' => 'video/x-sgi-movie' - ); - return (!isset($mimes[strtolower($ext)])) ? 'application/octet-stream' : $mimes[strtolower($ext)]; - } - - /** - * Set (or reset) Class Objects (variables) - * - * Usage Example: - * $page->set('X-Priority', '3'); - * - * @access public - * @param string $name - * @param mixed $value - * NOTE: will not work with arrays, there are no arrays to set/reset - * @throws phpmailerException - * @return bool - * @todo Should this not be using __set() magic function? - */ - public function set($name, $value = '') { - try { - if (isset($this->$name) ) { - $this->$name = $value; - } else { - throw new phpmailerException($this->Lang('variable_set') . $name, self::STOP_CRITICAL); - } - } catch (Exception $e) { - $this->SetError($e->getMessage()); - if ($e->getCode() == self::STOP_CRITICAL) { - return false; - } - } - return true; - } - - /** - * Strips newlines to prevent header injection. - * @access public - * @param string $str - * @return string - */ - public function SecureHeader($str) { - return trim(str_replace(array("\r", "\n"), '', $str)); - } - - /** - * Set the private key file and password to sign the message. - * - * @access public - * @param string $cert_filename - * @param string $key_filename - * @param string $key_pass Password for private key - */ - public function Sign($cert_filename, $key_filename, $key_pass) { - $this->sign_cert_file = $cert_filename; - $this->sign_key_file = $key_filename; - $this->sign_key_pass = $key_pass; - } - - /** - * Set the private key file and password to sign the message. - * - * @access public - * @param string $txt - * @return string - */ - public function DKIM_QP($txt) { - $line = ''; - for ($i = 0; $i < strlen($txt); $i++) { - $ord = ord($txt[$i]); - if ( ((0x21 <= $ord) && ($ord <= 0x3A)) || $ord == 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E)) ) { - $line .= $txt[$i]; - } else { - $line .= "=".sprintf("%02X", $ord); - } - } - return $line; - } - - /** - * Generate DKIM signature - * - * @access public - * @param string $s Header - * @throws phpmailerException - * @return string - */ - public function DKIM_Sign($s) { - if (!defined('PKCS7_TEXT')) { - if ($this->exceptions) { - throw new phpmailerException($this->Lang("signing").' OpenSSL extension missing.'); - } - return ''; - } - $privKeyStr = file_get_contents($this->DKIM_private); - if ($this->DKIM_passphrase != '') { - $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase); - } else { - $privKey = $privKeyStr; - } - if (openssl_sign($s, $signature, $privKey)) { - return base64_encode($signature); - } - return ''; - } - - /** - * Generate DKIM Canonicalization Header - * - * @access public - * @param string $s Header - * @return string - */ - public function DKIM_HeaderC($s) { - $s = preg_replace("/\r\n\s+/", " ", $s); - $lines = explode("\r\n", $s); - foreach ($lines as $key => $line) { - list($heading, $value) = explode(":", $line, 2); - $heading = strtolower($heading); - $value = preg_replace("/\s+/", " ", $value) ; // Compress useless spaces - $lines[$key] = $heading.":".trim($value) ; // Don't forget to remove WSP around the value - } - $s = implode("\r\n", $lines); - return $s; - } - - /** - * Generate DKIM Canonicalization Body - * - * @access public - * @param string $body Message Body - * @return string - */ - public function DKIM_BodyC($body) { - if ($body == '') return "\r\n"; - // stabilize line endings - $body = str_replace("\r\n", "\n", $body); - $body = str_replace("\n", "\r\n", $body); - // END stabilize line endings - while (substr($body, strlen($body) - 4, 4) == "\r\n\r\n") { - $body = substr($body, 0, strlen($body) - 2); - } - return $body; - } - - /** - * Create the DKIM header, body, as new header - * - * @access public - * @param string $headers_line Header lines - * @param string $subject Subject - * @param string $body Body - * @return string - */ - public function DKIM_Add($headers_line, $subject, $body) { - $DKIMsignatureType = 'rsa-sha1'; // Signature & hash algorithms - $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body - $DKIMquery = 'dns/txt'; // Query method - $DKIMtime = time() ; // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone) - $subject_header = "Subject: $subject"; - $headers = explode($this->LE, $headers_line); - $from_header = ''; - $to_header = ''; - $current = ''; - foreach($headers as $header) { - if (strpos($header, 'From:') === 0) { - $from_header = $header; - $current = 'from_header'; - } elseif (strpos($header, 'To:') === 0) { - $to_header = $header; - $current = 'to_header'; - } else { - if($current && strpos($header, ' =?') === 0){ - $$current .= $header; - } else { - $current = ''; - } - } - } - $from = str_replace('|', '=7C', $this->DKIM_QP($from_header)); - $to = str_replace('|', '=7C', $this->DKIM_QP($to_header)); - $subject = str_replace('|', '=7C', $this->DKIM_QP($subject_header)) ; // Copied header fields (dkim-quoted-printable - $body = $this->DKIM_BodyC($body); - $DKIMlen = strlen($body) ; // Length of body - $DKIMb64 = base64_encode(pack("H*", sha1($body))) ; // Base64 of packed binary SHA-1 hash of body - $ident = ($this->DKIM_identity == '')? '' : " i=" . $this->DKIM_identity . ";"; - $dkimhdrs = "DKIM-Signature: v=1; a=" . $DKIMsignatureType . "; q=" . $DKIMquery . "; l=" . $DKIMlen . "; s=" . $this->DKIM_selector . ";\r\n". - "\tt=" . $DKIMtime . "; c=" . $DKIMcanonicalization . ";\r\n". - "\th=From:To:Subject;\r\n". - "\td=" . $this->DKIM_domain . ";" . $ident . "\r\n". - "\tz=$from\r\n". - "\t|$to\r\n". - "\t|$subject;\r\n". - "\tbh=" . $DKIMb64 . ";\r\n". - "\tb="; - $toSign = $this->DKIM_HeaderC($from_header . "\r\n" . $to_header . "\r\n" . $subject_header . "\r\n" . $dkimhdrs); - $signed = $this->DKIM_Sign($toSign); - return $dkimhdrs.$signed."\r\n"; - } - - /** - * Perform callback - * @param boolean $isSent - * @param string $to - * @param string $cc - * @param string $bcc - * @param string $subject - * @param string $body - * @param string $from - */ - protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body, $from = null) { - if (!empty($this->action_function) && is_callable($this->action_function)) { - $params = array($isSent, $to, $cc, $bcc, $subject, $body, $from); - call_user_func_array($this->action_function, $params); - } - } -} - -/** - * Exception handler for PHPMailer - * @package PHPMailer - */ -class phpmailerException extends Exception { - /** - * Prettify error message output - * @return string - */ - public function errorMessage() { - $errorMsg = '' . $this->getMessage() . "
    \n"; - return $errorMsg; - } -} diff --git a/modules/phpmailer/class.pop3.php b/modules/phpmailer/class.pop3.php deleted file mode 100644 index 17bb6756f..000000000 --- a/modules/phpmailer/class.pop3.php +++ /dev/null @@ -1,418 +0,0 @@ - - * @author Andy Prevost - * @author Jim Jagielski - */ - -class POP3 { - /** - * Default POP3 port - * @var int - */ - public $POP3_PORT = 110; - - /** - * Default Timeout - * @var int - */ - public $POP3_TIMEOUT = 30; - - /** - * POP3 Carriage Return + Line Feed - * @var string - */ - public $CRLF = "\r\n"; - - /** - * Displaying Debug warnings? (0 = now, 1+ = yes) - * @var int - */ - public $do_debug = 2; - - /** - * POP3 Mail Server - * @var string - */ - public $host; - - /** - * POP3 Port - * @var int - */ - public $port; - - /** - * POP3 Timeout Value - * @var int - */ - public $tval; - - /** - * POP3 Username - * @var string - */ - public $username; - - /** - * POP3 Password - * @var string - */ - public $password; - - /** - * Sets the POP3 PHPMailer Version number - * @var string - */ - public $Version = '5.2.6'; - - ///////////////////////////////////////////////// - // PROPERTIES, PRIVATE AND PROTECTED - ///////////////////////////////////////////////// - - /** - * @var resource Resource handle for the POP connection socket - */ - private $pop_conn; - /** - * @var boolean Are we connected? - */ - private $connected; - /** - * @var array Error container - */ - private $error; // Error log array - - /** - * Constructor, sets the initial values - * @access public - * @return POP3 - */ - public function __construct() { - $this->pop_conn = 0; - $this->connected = false; - $this->error = null; - } - - /** - * Combination of public events - connect, login, disconnect - * @access public - * @param string $host - * @param bool|int $port - * @param bool|int $tval - * @param string $username - * @param string $password - * @param int $debug_level - * @return bool - */ - public function Authorise ($host, $port = false, $tval = false, $username, $password, $debug_level = 0) { - $this->host = $host; - - // If no port value is passed, retrieve it - if ($port == false) { - $this->port = $this->POP3_PORT; - } else { - $this->port = $port; - } - - // If no port value is passed, retrieve it - if ($tval == false) { - $this->tval = $this->POP3_TIMEOUT; - } else { - $this->tval = $tval; - } - - $this->do_debug = $debug_level; - $this->username = $username; - $this->password = $password; - - // Refresh the error log - $this->error = null; - - // Connect - $result = $this->Connect($this->host, $this->port, $this->tval); - - if ($result) { - $login_result = $this->Login($this->username, $this->password); - - if ($login_result) { - $this->Disconnect(); - - return true; - } - - } - - // We need to disconnect regardless if the login succeeded - $this->Disconnect(); - - return false; - } - - /** - * Connect to the POP3 server - * @access public - * @param string $host - * @param bool|int $port - * @param integer $tval - * @return boolean - */ - public function Connect ($host, $port = false, $tval = 30) { - // Are we already connected? - if ($this->connected) { - return true; - } - - /* - On Windows this will raise a PHP Warning error if the hostname doesn't exist. - Rather than supress it with @fsockopen, let's capture it cleanly instead - */ - - set_error_handler(array(&$this, 'catchWarning')); - - // Connect to the POP3 server - $this->pop_conn = fsockopen($host, // POP3 Host - $port, // Port # - $errno, // Error Number - $errstr, // Error Message - $tval); // Timeout (seconds) - - // Restore the error handler - restore_error_handler(); - - // Does the Error Log now contain anything? - if ($this->error && $this->do_debug >= 1) { - $this->displayErrors(); - } - - // Did we connect? - if ($this->pop_conn == false) { - // It would appear not... - $this->error = array( - 'error' => "Failed to connect to server $host on port $port", - 'errno' => $errno, - 'errstr' => $errstr - ); - - if ($this->do_debug >= 1) { - $this->displayErrors(); - } - - return false; - } - - // Increase the stream time-out - - // Check for PHP 4.3.0 or later - if (version_compare(phpversion(), '5.0.0', 'ge')) { - stream_set_timeout($this->pop_conn, $tval, 0); - } else { - // Does not work on Windows - if (substr(PHP_OS, 0, 3) !== 'WIN') { - socket_set_timeout($this->pop_conn, $tval, 0); - } - } - - // Get the POP3 server response - $pop3_response = $this->getResponse(); - - // Check for the +OK - if ($this->checkResponse($pop3_response)) { - // The connection is established and the POP3 server is talking - $this->connected = true; - return true; - } - return false; - } - - /** - * Login to the POP3 server (does not support APOP yet) - * @access public - * @param string $username - * @param string $password - * @return boolean - */ - public function Login ($username = '', $password = '') { - if ($this->connected == false) { - $this->error = 'Not connected to POP3 server'; - - if ($this->do_debug >= 1) { - $this->displayErrors(); - } - } - - if (empty($username)) { - $username = $this->username; - } - - if (empty($password)) { - $password = $this->password; - } - - $pop_username = "USER $username" . $this->CRLF; - $pop_password = "PASS $password" . $this->CRLF; - - // Send the Username - $this->sendString($pop_username); - $pop3_response = $this->getResponse(); - - if ($this->checkResponse($pop3_response)) { - // Send the Password - $this->sendString($pop_password); - $pop3_response = $this->getResponse(); - - if ($this->checkResponse($pop3_response)) { - return true; - } - } - return false; - } - - /** - * Disconnect from the POP3 server - * @access public - */ - public function Disconnect () { - $this->sendString('QUIT'); - - fclose($this->pop_conn); - } - - ///////////////////////////////////////////////// - // Private Methods - ///////////////////////////////////////////////// - - /** - * Get the socket response back. - * $size is the maximum number of bytes to retrieve - * @access private - * @param integer $size - * @return string - */ - private function getResponse ($size = 128) { - $pop3_response = fgets($this->pop_conn, $size); - - return $pop3_response; - } - - /** - * Send a string down the open socket connection to the POP3 server - * @access private - * @param string $string - * @return integer - */ - private function sendString ($string) { - $bytes_sent = fwrite($this->pop_conn, $string, strlen($string)); - - return $bytes_sent; - } - - /** - * Checks the POP3 server response for +OK or -ERR - * @access private - * @param string $string - * @return boolean - */ - private function checkResponse ($string) { - if (substr($string, 0, 3) !== '+OK') { - $this->error = array( - 'error' => "Server reported an error: $string", - 'errno' => 0, - 'errstr' => '' - ); - - if ($this->do_debug >= 1) { - $this->displayErrors(); - } - - return false; - } else { - return true; - } - - } - - /** - * If debug is enabled, display the error message array - * @access private - */ - private function displayErrors () { - echo '
    ';
    -
    -    foreach ($this->error as $single_error) {
    -      print_r($single_error);
    -    }
    -
    -    echo '
    '; - } - - /** - * Takes over from PHP for the socket warning handler - * @access private - * @param integer $errno - * @param string $errstr - * @param string $errfile - * @param integer $errline - */ - private function catchWarning ($errno, $errstr, $errfile, $errline) { - $this->error[] = array( - 'error' => "Connecting to the POP3 server raised a PHP warning: ", - 'errno' => $errno, - 'errstr' => $errstr - ); - } - - // End of class -} diff --git a/modules/phpmailer/class.smtp.php b/modules/phpmailer/class.smtp.php deleted file mode 100644 index 8444eb895..000000000 --- a/modules/phpmailer/class.smtp.php +++ /dev/null @@ -1,1088 +0,0 @@ -Debugoutput == 'error_log') { - error_log($str); - } else { - echo $str; - } - } - - /** - * Initialize the class so that the data is in a known state. - * @access public - * @return SMTP - */ - public function __construct() { - $this->smtp_conn = 0; - $this->error = null; - $this->helo_rply = null; - - $this->do_debug = 0; - } - - ///////////////////////////////////////////////// - // CONNECTION FUNCTIONS - ///////////////////////////////////////////////// - - /** - * Connect to the server specified on the port specified. - * If the port is not specified use the default SMTP_PORT. - * If tval is specified then a connection will try and be - * established with the server for that number of seconds. - * If tval is not specified the default is 30 seconds to - * try on the connection. - * - * SMTP CODE SUCCESS: 220 - * SMTP CODE FAILURE: 421 - * @access public - * @param string $host - * @param int $port - * @param int $tval - * @return bool - */ - public function Connect($host, $port = 0, $tval = 30) { - // set the error val to null so there is no confusion - $this->error = null; - - // make sure we are __not__ connected - if($this->connected()) { - // already connected, generate error - $this->error = array('error' => 'Already connected to a server'); - return false; - } - - if(empty($port)) { - $port = $this->SMTP_PORT; - } - - // connect to the smtp server - $this->smtp_conn = @fsockopen($host, // the host of the server - $port, // the port to use - $errno, // error number if any - $errstr, // error message if any - $tval); // give up after ? secs - // verify we connected properly - if(empty($this->smtp_conn)) { - $this->error = array('error' => 'Failed to connect to server', - 'errno' => $errno, - 'errstr' => $errstr); - if($this->do_debug >= 1) { - $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ": $errstr ($errno)" . $this->CRLF . '
    '); - } - return false; - } - - // SMTP server can take longer to respond, give longer timeout for first read - // Windows does not have support for this timeout function - if(substr(PHP_OS, 0, 3) != 'WIN') { - $max = ini_get('max_execution_time'); - if ($max != 0 && $tval > $max) { // don't bother if unlimited - @set_time_limit($tval); - } - stream_set_timeout($this->smtp_conn, $tval, 0); - } - - // get any announcement - $announce = $this->get_lines(); - - if($this->do_debug >= 2) { - $this->edebug('SMTP -> FROM SERVER:' . $announce . $this->CRLF . '
    '); - } - - return true; - } - - /** - * Initiate a TLS communication with the server. - * - * SMTP CODE 220 Ready to start TLS - * SMTP CODE 501 Syntax error (no parameters allowed) - * SMTP CODE 454 TLS not available due to temporary reason - * @access public - * @return bool success - */ - public function StartTLS() { - $this->error = null; # to avoid confusion - - if(!$this->connected()) { - $this->error = array('error' => 'Called StartTLS() without being connected'); - return false; - } - - $this->client_send('STARTTLS' . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply, 0, 3); - - if($this->do_debug >= 2) { - $this->edebug('SMTP -> FROM SERVER:' . $rply . $this->CRLF . '
    '); - } - - if($code != 220) { - $this->error = - array('error' => 'STARTTLS not accepted from server', - 'smtp_code' => $code, - 'smtp_msg' => substr($rply, 4)); - if($this->do_debug >= 1) { - $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply . $this->CRLF . '
    '); - } - return false; - } - - // Begin encrypted connection - if(!stream_socket_enable_crypto($this->smtp_conn, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) { - return false; - } - - return true; - } - - /** - * Performs SMTP authentication. Must be run after running the - * Hello() method. Returns true if successfully authenticated. - * @access public - * @param string $username - * @param string $password - * @param string $authtype - * @param string $realm - * @param string $workstation - * @return bool - */ - public function Authenticate($username, $password, $authtype='LOGIN', $realm='', $workstation='') { - if (empty($authtype)) { - $authtype = 'LOGIN'; - } - - switch ($authtype) { - case 'PLAIN': - // Start authentication - $this->client_send('AUTH PLAIN' . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply, 0, 3); - - if($code != 334) { - $this->error = - array('error' => 'AUTH not accepted from server', - 'smtp_code' => $code, - 'smtp_msg' => substr($rply, 4)); - if($this->do_debug >= 1) { - $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply . $this->CRLF . '
    '); - } - return false; - } - // Send encoded username and password - $this->client_send(base64_encode("\0".$username."\0".$password) . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply, 0, 3); - - if($code != 235) { - $this->error = - array('error' => 'Authentication not accepted from server', - 'smtp_code' => $code, - 'smtp_msg' => substr($rply, 4)); - if($this->do_debug >= 1) { - $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply . $this->CRLF . '
    '); - } - return false; - } - break; - case 'LOGIN': - // Start authentication - $this->client_send('AUTH LOGIN' . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply, 0, 3); - - if($code != 334) { - $this->error = - array('error' => 'AUTH not accepted from server', - 'smtp_code' => $code, - 'smtp_msg' => substr($rply, 4)); - if($this->do_debug >= 1) { - $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply . $this->CRLF . '
    '); - } - return false; - } - - // Send encoded username - $this->client_send(base64_encode($username) . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply, 0, 3); - - if($code != 334) { - $this->error = - array('error' => 'Username not accepted from server', - 'smtp_code' => $code, - 'smtp_msg' => substr($rply, 4)); - if($this->do_debug >= 1) { - $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply . $this->CRLF . '
    '); - } - return false; - } - - // Send encoded password - $this->client_send(base64_encode($password) . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply, 0, 3); - - if($code != 235) { - $this->error = - array('error' => 'Password not accepted from server', - 'smtp_code' => $code, - 'smtp_msg' => substr($rply, 4)); - if($this->do_debug >= 1) { - $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply . $this->CRLF . '
    '); - } - return false; - } - break; - case 'NTLM': - /* - * ntlm_sasl_client.php - ** Bundled with Permission - ** - ** How to telnet in windows: http://technet.microsoft.com/en-us/library/aa995718%28EXCHG.65%29.aspx - ** PROTOCOL Documentation http://curl.haxx.se/rfc/ntlm.html#ntlmSmtpAuthentication - */ - require_once 'extras/ntlm_sasl_client.php'; - $temp = new stdClass(); - $ntlm_client = new ntlm_sasl_client_class; - if(! $ntlm_client->Initialize($temp)){//let's test if every function its available - $this->error = array('error' => $temp->error); - if($this->do_debug >= 1) { - $this->edebug('You need to enable some modules in your php.ini file: ' . $this->error['error'] . $this->CRLF); - } - return false; - } - $msg1 = $ntlm_client->TypeMsg1($realm, $workstation);//msg1 - - $this->client_send('AUTH NTLM ' . base64_encode($msg1) . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply, 0, 3); - - - if($code != 334) { - $this->error = - array('error' => 'AUTH not accepted from server', - 'smtp_code' => $code, - 'smtp_msg' => substr($rply, 4)); - if($this->do_debug >= 1) { - $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply . $this->CRLF); - } - return false; - } - - $challenge = substr($rply, 3);//though 0 based, there is a white space after the 3 digit number....//msg2 - $challenge = base64_decode($challenge); - $ntlm_res = $ntlm_client->NTLMResponse(substr($challenge, 24, 8), $password); - $msg3 = $ntlm_client->TypeMsg3($ntlm_res, $username, $realm, $workstation);//msg3 - // Send encoded username - $this->client_send(base64_encode($msg3) . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply, 0, 3); - - if($code != 235) { - $this->error = - array('error' => 'Could not authenticate', - 'smtp_code' => $code, - 'smtp_msg' => substr($rply, 4)); - if($this->do_debug >= 1) { - $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply . $this->CRLF); - } - return false; - } - break; - case 'CRAM-MD5': - // Start authentication - $this->client_send('AUTH CRAM-MD5' . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply, 0, 3); - - if($code != 334) { - $this->error = - array('error' => 'AUTH not accepted from server', - 'smtp_code' => $code, - 'smtp_msg' => substr($rply, 4)); - if($this->do_debug >= 1) { - $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply . $this->CRLF . '
    '); - } - return false; - } - - // Get the challenge - $challenge = base64_decode(substr($rply, 4)); - - // Build the response - $response = $username . ' ' . $this->hmac($challenge, $password); - - // Send encoded credentials - $this->client_send(base64_encode($response) . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply, 0, 3); - - if($code != 334) { - $this->error = - array('error' => 'Credentials not accepted from server', - 'smtp_code' => $code, - 'smtp_msg' => substr($rply, 4)); - if($this->do_debug >= 1) { - $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply . $this->CRLF . '
    '); - } - return false; - } - break; - } - return true; - } - - /** - * Works like hash_hmac('md5', $data, $key) in case that function is not available - * @access private - * @param string $data - * @param string $key - * @return string - */ - private function hmac($data, $key) { - if (function_exists('hash_hmac')) { - return hash_hmac('md5', $data, $key); - } - - // The following borrowed from http://php.net/manual/en/function.mhash.php#27225 - - // RFC 2104 HMAC implementation for php. - // Creates an md5 HMAC. - // Eliminates the need to install mhash to compute a HMAC - // Hacked by Lance Rushing - - $b = 64; // byte length for md5 - if (strlen($key) > $b) { - $key = pack('H*', md5($key)); - } - $key = str_pad($key, $b, chr(0x00)); - $ipad = str_pad('', $b, chr(0x36)); - $opad = str_pad('', $b, chr(0x5c)); - $k_ipad = $key ^ $ipad ; - $k_opad = $key ^ $opad; - - return md5($k_opad . pack('H*', md5($k_ipad . $data))); - } - - /** - * Returns true if connected to a server otherwise false - * @access public - * @return bool - */ - public function Connected() { - if(!empty($this->smtp_conn)) { - $sock_status = stream_get_meta_data($this->smtp_conn); - if($sock_status['eof']) { - // the socket is valid but we are not connected - if($this->do_debug >= 1) { - $this->edebug('SMTP -> NOTICE:' . $this->CRLF . 'EOF caught while checking if connected'); - } - $this->Close(); - return false; - } - return true; // everything looks good - } - return false; - } - - /** - * Closes the socket and cleans up the state of the class. - * It is not considered good to use this function without - * first trying to use QUIT. - * @access public - * @return void - */ - public function Close() { - $this->error = null; // so there is no confusion - $this->helo_rply = null; - if(!empty($this->smtp_conn)) { - // close the connection and cleanup - fclose($this->smtp_conn); - $this->smtp_conn = 0; - } - } - - ///////////////////////////////////////////////// - // SMTP COMMANDS - ///////////////////////////////////////////////// - - /** - * Issues a data command and sends the msg_data to the server - * finializing the mail transaction. $msg_data is the message - * that is to be send with the headers. Each header needs to be - * on a single line followed by a with the message headers - * and the message body being seperated by and additional . - * - * Implements rfc 821: DATA - * - * SMTP CODE INTERMEDIATE: 354 - * [data] - * . - * SMTP CODE SUCCESS: 250 - * SMTP CODE FAILURE: 552, 554, 451, 452 - * SMTP CODE FAILURE: 451, 554 - * SMTP CODE ERROR : 500, 501, 503, 421 - * @access public - * @param string $msg_data - * @return bool - */ - public function Data($msg_data) { - $this->error = null; // so no confusion is caused - - if(!$this->connected()) { - $this->error = array( - 'error' => 'Called Data() without being connected'); - return false; - } - - $this->client_send('DATA' . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply, 0, 3); - - if($this->do_debug >= 2) { - $this->edebug('SMTP -> FROM SERVER:' . $rply . $this->CRLF . '
    '); - } - - if($code != 354) { - $this->error = - array('error' => 'DATA command not accepted from server', - 'smtp_code' => $code, - 'smtp_msg' => substr($rply, 4)); - if($this->do_debug >= 1) { - $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply . $this->CRLF . '
    '); - } - return false; - } - - /* the server is ready to accept data! - * according to rfc 821 we should not send more than 1000 - * including the CRLF - * characters on a single line so we will break the data up - * into lines by \r and/or \n then if needed we will break - * each of those into smaller lines to fit within the limit. - * in addition we will be looking for lines that start with - * a period '.' and append and additional period '.' to that - * line. NOTE: this does not count towards limit. - */ - - // normalize the line breaks so we know the explode works - $msg_data = str_replace("\r\n", "\n", $msg_data); - $msg_data = str_replace("\r", "\n", $msg_data); - $lines = explode("\n", $msg_data); - - /* we need to find a good way to determine is headers are - * in the msg_data or if it is a straight msg body - * currently I am assuming rfc 822 definitions of msg headers - * and if the first field of the first line (':' sperated) - * does not contain a space then it _should_ be a header - * and we can process all lines before a blank "" line as - * headers. - */ - - $field = substr($lines[0], 0, strpos($lines[0], ':')); - $in_headers = false; - if(!empty($field) && !strstr($field, ' ')) { - $in_headers = true; - } - - $max_line_length = 998; // used below; set here for ease in change - - while(list(, $line) = @each($lines)) { - $lines_out = null; - if($line == '' && $in_headers) { - $in_headers = false; - } - // ok we need to break this line up into several smaller lines - while(strlen($line) > $max_line_length) { - $pos = strrpos(substr($line, 0, $max_line_length), ' '); - - // Patch to fix DOS attack - if(!$pos) { - $pos = $max_line_length - 1; - $lines_out[] = substr($line, 0, $pos); - $line = substr($line, $pos); - } else { - $lines_out[] = substr($line, 0, $pos); - $line = substr($line, $pos + 1); - } - - /* if processing headers add a LWSP-char to the front of new line - * rfc 822 on long msg headers - */ - if($in_headers) { - $line = "\t" . $line; - } - } - $lines_out[] = $line; - - // send the lines to the server - while(list(, $line_out) = @each($lines_out)) { - if(strlen($line_out) > 0) - { - if(substr($line_out, 0, 1) == '.') { - $line_out = '.' . $line_out; - } - } - $this->client_send($line_out . $this->CRLF); - } - } - - // message data has been sent - $this->client_send($this->CRLF . '.' . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply, 0, 3); - - if($this->do_debug >= 2) { - $this->edebug('SMTP -> FROM SERVER:' . $rply . $this->CRLF . '
    '); - } - - if($code != 250) { - $this->error = - array('error' => 'DATA not accepted from server', - 'smtp_code' => $code, - 'smtp_msg' => substr($rply, 4)); - if($this->do_debug >= 1) { - $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply . $this->CRLF . '
    '); - } - return false; - } - return true; - } - - /** - * Sends the HELO command to the smtp server. - * This makes sure that we and the server are in - * the same known state. - * - * Implements from rfc 821: HELO - * - * SMTP CODE SUCCESS: 250 - * SMTP CODE ERROR : 500, 501, 504, 421 - * @access public - * @param string $host - * @return bool - */ - public function Hello($host = '') { - $this->error = null; // so no confusion is caused - - if(!$this->connected()) { - $this->error = array( - 'error' => 'Called Hello() without being connected'); - return false; - } - - // if hostname for HELO was not specified send default - if(empty($host)) { - // determine appropriate default to send to server - $host = 'localhost'; - } - - // Send extended hello first (RFC 2821) - if(!$this->SendHello('EHLO', $host)) { - if(!$this->SendHello('HELO', $host)) { - return false; - } - } - - return true; - } - - /** - * Sends a HELO/EHLO command. - * @access private - * @param string $hello - * @param string $host - * @return bool - */ - private function SendHello($hello, $host) { - $this->client_send($hello . ' ' . $host . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply, 0, 3); - - if($this->do_debug >= 2) { - $this->edebug('SMTP -> FROM SERVER: ' . $rply . $this->CRLF . '
    '); - } - - if($code != 250) { - $this->error = - array('error' => $hello . ' not accepted from server', - 'smtp_code' => $code, - 'smtp_msg' => substr($rply, 4)); - if($this->do_debug >= 1) { - $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply . $this->CRLF . '
    '); - } - return false; - } - - $this->helo_rply = $rply; - - return true; - } - - /** - * Starts a mail transaction from the email address specified in - * $from. Returns true if successful or false otherwise. If True - * the mail transaction is started and then one or more Recipient - * commands may be called followed by a Data command. - * - * Implements rfc 821: MAIL FROM: - * - * SMTP CODE SUCCESS: 250 - * SMTP CODE SUCCESS: 552, 451, 452 - * SMTP CODE SUCCESS: 500, 501, 421 - * @access public - * @param string $from - * @return bool - */ - public function Mail($from) { - $this->error = null; // so no confusion is caused - - if(!$this->connected()) { - $this->error = array( - 'error' => 'Called Mail() without being connected'); - return false; - } - - $useVerp = ($this->do_verp ? ' XVERP' : ''); - $this->client_send('MAIL FROM:<' . $from . '>' . $useVerp . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply, 0, 3); - - if($this->do_debug >= 2) { - $this->edebug('SMTP -> FROM SERVER:' . $rply . $this->CRLF . '
    '); - } - - if($code != 250) { - $this->error = - array('error' => 'MAIL not accepted from server', - 'smtp_code' => $code, - 'smtp_msg' => substr($rply, 4)); - if($this->do_debug >= 1) { - $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply . $this->CRLF . '
    '); - } - return false; - } - return true; - } - - /** - * Sends the quit command to the server and then closes the socket - * if there is no error or the $close_on_error argument is true. - * - * Implements from rfc 821: QUIT - * - * SMTP CODE SUCCESS: 221 - * SMTP CODE ERROR : 500 - * @access public - * @param bool $close_on_error - * @return bool - */ - public function Quit($close_on_error = true) { - $this->error = null; // so there is no confusion - - if(!$this->connected()) { - $this->error = array( - 'error' => 'Called Quit() without being connected'); - return false; - } - - // send the quit command to the server - $this->client_send('quit' . $this->CRLF); - - // get any good-bye messages - $byemsg = $this->get_lines(); - - if($this->do_debug >= 2) { - $this->edebug('SMTP -> FROM SERVER:' . $byemsg . $this->CRLF . '
    '); - } - - $rval = true; - $e = null; - - $code = substr($byemsg, 0, 3); - if($code != 221) { - // use e as a tmp var cause Close will overwrite $this->error - $e = array('error' => 'SMTP server rejected quit command', - 'smtp_code' => $code, - 'smtp_rply' => substr($byemsg, 4)); - $rval = false; - if($this->do_debug >= 1) { - $this->edebug('SMTP -> ERROR: ' . $e['error'] . ': ' . $byemsg . $this->CRLF . '
    '); - } - } - - if(empty($e) || $close_on_error) { - $this->Close(); - } - - return $rval; - } - - /** - * Sends the command RCPT to the SMTP server with the TO: argument of $to. - * Returns true if the recipient was accepted false if it was rejected. - * - * Implements from rfc 821: RCPT TO: - * - * SMTP CODE SUCCESS: 250, 251 - * SMTP CODE FAILURE: 550, 551, 552, 553, 450, 451, 452 - * SMTP CODE ERROR : 500, 501, 503, 421 - * @access public - * @param string $to - * @return bool - */ - public function Recipient($to) { - $this->error = null; // so no confusion is caused - - if(!$this->connected()) { - $this->error = array( - 'error' => 'Called Recipient() without being connected'); - return false; - } - - $this->client_send('RCPT TO:<' . $to . '>' . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply, 0, 3); - - if($this->do_debug >= 2) { - $this->edebug('SMTP -> FROM SERVER:' . $rply . $this->CRLF . '
    '); - } - - if($code != 250 && $code != 251) { - $this->error = - array('error' => 'RCPT not accepted from server', - 'smtp_code' => $code, - 'smtp_msg' => substr($rply, 4)); - if($this->do_debug >= 1) { - $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply . $this->CRLF . '
    '); - } - return false; - } - return true; - } - - /** - * Sends the RSET command to abort and transaction that is - * currently in progress. Returns true if successful false - * otherwise. - * - * Implements rfc 821: RSET - * - * SMTP CODE SUCCESS: 250 - * SMTP CODE ERROR : 500, 501, 504, 421 - * @access public - * @return bool - */ - public function Reset() { - $this->error = null; // so no confusion is caused - - if(!$this->connected()) { - $this->error = array('error' => 'Called Reset() without being connected'); - return false; - } - - $this->client_send('RSET' . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply, 0, 3); - - if($this->do_debug >= 2) { - $this->edebug('SMTP -> FROM SERVER:' . $rply . $this->CRLF . '
    '); - } - - if($code != 250) { - $this->error = - array('error' => 'RSET failed', - 'smtp_code' => $code, - 'smtp_msg' => substr($rply, 4)); - if($this->do_debug >= 1) { - $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply . $this->CRLF . '
    '); - } - return false; - } - - return true; - } - - /** - * Starts a mail transaction from the email address specified in - * $from. Returns true if successful or false otherwise. If True - * the mail transaction is started and then one or more Recipient - * commands may be called followed by a Data command. This command - * will send the message to the users terminal if they are logged - * in and send them an email. - * - * Implements rfc 821: SAML FROM: - * - * SMTP CODE SUCCESS: 250 - * SMTP CODE SUCCESS: 552, 451, 452 - * SMTP CODE SUCCESS: 500, 501, 502, 421 - * @access public - * @param string $from - * @return bool - */ - public function SendAndMail($from) { - $this->error = null; // so no confusion is caused - - if(!$this->connected()) { - $this->error = array( - 'error' => 'Called SendAndMail() without being connected'); - return false; - } - - $this->client_send('SAML FROM:' . $from . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply, 0, 3); - - if($this->do_debug >= 2) { - $this->edebug('SMTP -> FROM SERVER:' . $rply . $this->CRLF . '
    '); - } - - if($code != 250) { - $this->error = - array('error' => 'SAML not accepted from server', - 'smtp_code' => $code, - 'smtp_msg' => substr($rply, 4)); - if($this->do_debug >= 1) { - $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply . $this->CRLF . '
    '); - } - return false; - } - return true; - } - - /** - * This is an optional command for SMTP that this class does not - * support. This method is here to make the RFC821 Definition - * complete for this class and __may__ be implimented in the future - * - * Implements from rfc 821: TURN - * - * SMTP CODE SUCCESS: 250 - * SMTP CODE FAILURE: 502 - * SMTP CODE ERROR : 500, 503 - * @access public - * @return bool - */ - public function Turn() { - $this->error = array('error' => 'This method, TURN, of the SMTP '. - 'is not implemented'); - if($this->do_debug >= 1) { - $this->edebug('SMTP -> NOTICE: ' . $this->error['error'] . $this->CRLF . '
    '); - } - return false; - } - - /** - * Sends data to the server - * @param string $data - * @access public - * @return Integer number of bytes sent to the server or FALSE on error - */ - public function client_send($data) { - if ($this->do_debug >= 1) { - $this->edebug("CLIENT -> SMTP: $data" . $this->CRLF . '
    '); - } - return fwrite($this->smtp_conn, $data); - } - - /** - * Get the current error - * @access public - * @return array - */ - public function getError() { - return $this->error; - } - - ///////////////////////////////////////////////// - // INTERNAL FUNCTIONS - ///////////////////////////////////////////////// - - /** - * Read in as many lines as possible - * either before eof or socket timeout occurs on the operation. - * With SMTP we can tell if we have more lines to read if the - * 4th character is '-' symbol. If it is a space then we don't - * need to read anything else. - * @access private - * @return string - */ - private function get_lines() { - $data = ''; - $endtime = 0; - /* If for some reason the fp is bad, don't inf loop */ - if (!is_resource($this->smtp_conn)) { - return $data; - } - stream_set_timeout($this->smtp_conn, $this->Timeout); - if ($this->Timelimit > 0) { - $endtime = time() + $this->Timelimit; - } - while(is_resource($this->smtp_conn) && !feof($this->smtp_conn)) { - $str = @fgets($this->smtp_conn, 515); - if($this->do_debug >= 4) { - $this->edebug("SMTP -> get_lines(): \$data was \"$data\"" . $this->CRLF . '
    '); - $this->edebug("SMTP -> get_lines(): \$str is \"$str\"" . $this->CRLF . '
    '); - } - $data .= $str; - if($this->do_debug >= 4) { - $this->edebug("SMTP -> get_lines(): \$data is \"$data\"" . $this->CRLF . '
    '); - } - // if 4th character is a space, we are done reading, break the loop - if(substr($str, 3, 1) == ' ') { break; } - // Timed-out? Log and break - $info = stream_get_meta_data($this->smtp_conn); - if ($info['timed_out']) { - if($this->do_debug >= 4) { - $this->edebug('SMTP -> get_lines(): timed-out (' . $this->Timeout . ' seconds)
    '); - } - break; - } - // Now check if reads took too long - if ($endtime) { - if (time() > $endtime) { - if($this->do_debug >= 4) { - $this->edebug('SMTP -> get_lines(): timelimit reached (' . $this->Timelimit . ' seconds)
    '); - } - break; - } - } - } - return $data; - } - -} diff --git a/modules/phpmailer/composer.json b/modules/phpmailer/composer.json deleted file mode 100644 index fb772097d..000000000 --- a/modules/phpmailer/composer.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "name": "phpmailer/phpmailer", - "description": "PHPMailer is a full-featured email creation and transfer class for PHP", - "authors": [ - { - "name": "Jim Jagielski", - "email": "jimjag@gmail.com" - }, - { - "name": "Marcus Bointon", - "email": "phpmailer@synchromedia.co.uk" - }, - { - "name": "Andy Prevost", - "email": "codeworxtech@users.sourceforge.net" - }, - { - "name": "Brent R. Matzelle" - } - ], - "require": { - "php": ">=5.0.0" - }, - "require-dev": { - "phpdocumentor/phpdocumentor": "*", - "phpunit/phpunit": "*" - }, - "autoload": { - "classmap": ["class.phpmailer.php", "class.pop3.php", "class.smtp.php"] - }, - "license": "LGPL-2.1" -} \ No newline at end of file diff --git a/modules/phpmailer/extras/class.html2text.php b/modules/phpmailer/extras/class.html2text.php deleted file mode 100644 index 4dcd5accf..000000000 --- a/modules/phpmailer/extras/class.html2text.php +++ /dev/null @@ -1,696 +0,0 @@ - * - * This version from https://github.com/mtibben/html2text * - * * - * This script is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * * - * The GNU General Public License can be found at * - * http://www.gnu.org/copyleft/gpl.html. * - * * - * This script is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU General Public License for more details. * - * * - *************************************************************************/ - - -class html2text -{ - - /** - * Contains the HTML content to convert. - * - * @var string $html - * @access public - */ - public $html; - - /** - * Contains the converted, formatted text. - * - * @var string $text - * @access public - */ - public $text; - - /** - * Maximum width of the formatted text, in columns. - * - * Set this value to 0 (or less) to ignore word wrapping - * and not constrain text to a fixed-width column. - * - * @var integer $width - * @access public - */ - public $width = 70; - - /** - * List of preg* regular expression patterns to search for, - * used in conjunction with $replace. - * - * @var array $search - * @access public - * @see $replace - */ - public $search = array( - "/\r/", // Non-legal carriage return - "/[\n\t]+/", // Newlines and tabs - '/]*>.*?<\/head>/i', // - '/]*>.*?<\/script>/i', // - - '; -} - - - - -/** - * A ReCaptchaResponse is returned from recaptcha_check_answer() - */ -class ReCaptchaResponse { - var $is_valid; - var $error; -} - - -/** - * Calls an HTTP POST function to verify if the user's guess was correct - * @param string $privkey - * @param string $remoteip - * @param string $challenge - * @param string $response - * @param array $extra_params an array of extra variables to post to the server - * @return ReCaptchaResponse - */ -function recaptcha_check_answer ($privkey, $remoteip, $challenge, $response, $extra_params = array()) -{ - if ($privkey == null || $privkey == '') { - die ("To use reCAPTCHA you must get an API key from https://www.google.com/recaptcha/admin/create"); - } - - if ($remoteip == null || $remoteip == '') { - die ("For security reasons, you must pass the remote ip to reCAPTCHA"); - } - - - - //discard spam submissions - if ($challenge == null || strlen($challenge) == 0 || $response == null || strlen($response) == 0) { - $recaptcha_response = new ReCaptchaResponse(); - $recaptcha_response->is_valid = false; - $recaptcha_response->error = 'incorrect-captcha-sol'; - return $recaptcha_response; - } - - $response = _recaptcha_http_post (RECAPTCHA_VERIFY_SERVER, "/recaptcha/api/verify", - array ( - 'privatekey' => $privkey, - 'remoteip' => $remoteip, - 'challenge' => $challenge, - 'response' => $response - ) + $extra_params - ); - - $answers = explode ("\n", $response [1]); - $recaptcha_response = new ReCaptchaResponse(); - - if (trim ($answers [0]) == 'true') { - $recaptcha_response->is_valid = true; - } - else { - $recaptcha_response->is_valid = false; - $recaptcha_response->error = $answers [1]; - } - return $recaptcha_response; - -} - -/** - * gets a URL where the user can sign up for reCAPTCHA. If your application - * has a configuration page where you enter a key, you should provide a link - * using this function. - * @param string $domain The domain where the page is hosted - * @param string $appname The name of your application - */ -function recaptcha_get_signup_url ($domain = null, $appname = null) { - return "https://www.google.com/recaptcha/admin/create?" . _recaptcha_qsencode (array ('domains' => $domain, 'app' => $appname)); -} - -function _recaptcha_aes_pad($val) { - $block_size = 16; - $numpad = $block_size - (strlen ($val) % $block_size); - return str_pad($val, strlen ($val) + $numpad, chr($numpad)); -} - -/* Mailhide related code */ - -function _recaptcha_aes_encrypt($val,$ky) { - if (! function_exists ("mcrypt_encrypt")) { - die ("To use reCAPTCHA Mailhide, you need to have the mcrypt php module installed."); - } - $mode=MCRYPT_MODE_CBC; - $enc=MCRYPT_RIJNDAEL_128; - $val=_recaptcha_aes_pad($val); - return mcrypt_encrypt($enc, $ky, $val, $mode, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"); -} - - -function _recaptcha_mailhide_urlbase64 ($x) { - return strtr(base64_encode ($x), '+/', '-_'); -} - -/* gets the reCAPTCHA Mailhide url for a given email, public key and private key */ -function recaptcha_mailhide_url($pubkey, $privkey, $email) { - if ($pubkey == '' || $pubkey == null || $privkey == "" || $privkey == null) { - die ("To use reCAPTCHA Mailhide, you have to sign up for a public and private key, " . - "you can do so at http://www.google.com/recaptcha/mailhide/apikey"); - } - - - $ky = pack('H*', $privkey); - $cryptmail = _recaptcha_aes_encrypt ($email, $ky); - - return "http://www.google.com/recaptcha/mailhide/d?k=" . $pubkey . "&c=" . _recaptcha_mailhide_urlbase64 ($cryptmail); -} - -/** - * gets the parts of the email to expose to the user. - * eg, given johndoe@example,com return ["john", "example.com"]. - * the email is then displayed as john...@example.com - */ -function _recaptcha_mailhide_email_parts ($email) { - $arr = preg_split("/@/", $email ); - - if (strlen ($arr[0]) <= 4) { - $arr[0] = substr ($arr[0], 0, 1); - } else if (strlen ($arr[0]) <= 6) { - $arr[0] = substr ($arr[0], 0, 3); - } else { - $arr[0] = substr ($arr[0], 0, 4); - } - return $arr; -} - -/** - * Gets html to display an email address given a public an private key. - * to get a key, go to: - * - * http://www.google.com/recaptcha/mailhide/apikey - */ -function recaptcha_mailhide_html($pubkey, $privkey, $email) { - $emailparts = _recaptcha_mailhide_email_parts ($email); - $url = recaptcha_mailhide_url ($pubkey, $privkey, $email); - - return htmlentities($emailparts[0]) . "...@" . htmlentities ($emailparts [1]); - -} - - -?> diff --git a/modules/recaptchav2/ReCaptcha/ReCaptcha.php b/modules/recaptchav2/ReCaptcha/ReCaptcha.php new file mode 100644 index 000000000..bda769c8e --- /dev/null +++ b/modules/recaptchav2/ReCaptcha/ReCaptcha.php @@ -0,0 +1,98 @@ +secret = $secret; + + if (!is_null($requestMethod)) { + $this->requestMethod = $requestMethod; + } else { + $this->requestMethod = new RequestMethod\Post(); + } + } + + /** + * Calls the reCAPTCHA siteverify API to verify whether the user passes + * CAPTCHA test. + * + * @param string $response The value of 'g-recaptcha-response' in the submitted form. + * @param string $remoteIp The end user's IP address. + * @return Response Response from the service. + */ + public function verify($response, $remoteIp = null) + { + // Discard empty solution submissions + if (empty($response)) { + $recaptchaResponse = new Response(false, array('missing-input-response')); + return $recaptchaResponse; + } + + $params = new RequestParameters($this->secret, $response, $remoteIp, self::VERSION); + $rawResponse = $this->requestMethod->submit($params); + return Response::fromJson($rawResponse); + } +} diff --git a/modules/recaptchav2/ReCaptcha/RequestMethod.php b/modules/recaptchav2/ReCaptcha/RequestMethod.php new file mode 100644 index 000000000..fc4dde59c --- /dev/null +++ b/modules/recaptchav2/ReCaptcha/RequestMethod.php @@ -0,0 +1,42 @@ +curl = $curl; + } else { + $this->curl = new Curl(); + } + } + + /** + * Submit the cURL request with the specified parameters. + * + * @param RequestParameters $params Request parameters + * @return string Body of the reCAPTCHA response + */ + public function submit(RequestParameters $params) + { + $handle = $this->curl->init(self::SITE_VERIFY_URL); + + $options = array( + CURLOPT_POST => true, + CURLOPT_POSTFIELDS => $params->toQueryString(), + CURLOPT_HTTPHEADER => array( + 'Content-Type: application/x-www-form-urlencoded' + ), + CURLINFO_HEADER_OUT => false, + CURLOPT_HEADER => false, + CURLOPT_RETURNTRANSFER => true, + CURLOPT_SSL_VERIFYPEER => true + ); + $this->curl->setoptArray($handle, $options); + + $response = $this->curl->exec($handle); + $this->curl->close($handle); + + return $response; + } +} diff --git a/modules/recaptchav2/ReCaptcha/RequestMethod/Post.php b/modules/recaptchav2/ReCaptcha/RequestMethod/Post.php new file mode 100644 index 000000000..ace5084f4 --- /dev/null +++ b/modules/recaptchav2/ReCaptcha/RequestMethod/Post.php @@ -0,0 +1,74 @@ + array( + 'header' => "Content-type: application/x-www-form-urlencoded\r\n", + 'method' => 'POST', + 'content' => $params->toQueryString(), + // Force the peer to validate (not needed in 5.6.0+, but still works) + 'verify_peer' => false, + // Force the peer validation to use www.google.com + $peer_key => 'www.google.com', + ), + "ssl" => array( + "verify_peer"=>false, + "verify_peer_name"=>false, + ) + ); + $context = stream_context_create($options); + return file_get_contents(self::SITE_VERIFY_URL, false, $context); + } +} diff --git a/modules/recaptchav2/ReCaptcha/RequestMethod/Socket.php b/modules/recaptchav2/ReCaptcha/RequestMethod/Socket.php new file mode 100644 index 000000000..f51f1239a --- /dev/null +++ b/modules/recaptchav2/ReCaptcha/RequestMethod/Socket.php @@ -0,0 +1,104 @@ +handle = fsockopen($hostname, $port, $errno, $errstr, (is_null($timeout) ? ini_get("default_socket_timeout") : $timeout)); + + if ($this->handle != false && $errno === 0 && $errstr === '') { + return $this->handle; + } + return false; + } + + /** + * fwrite + * + * @see http://php.net/fwrite + * @param string $string + * @param int $length + * @return int | bool + */ + public function fwrite($string, $length = null) + { + return fwrite($this->handle, $string, (is_null($length) ? strlen($string) : $length)); + } + + /** + * fgets + * + * @see http://php.net/fgets + * @param int $length + * @return string + */ + public function fgets($length = null) + { + return fgets($this->handle, $length); + } + + /** + * feof + * + * @see http://php.net/feof + * @return bool + */ + public function feof() + { + return feof($this->handle); + } + + /** + * fclose + * + * @see http://php.net/fclose + * @return bool + */ + public function fclose() + { + return fclose($this->handle); + } +} diff --git a/modules/recaptchav2/ReCaptcha/RequestMethod/SocketPost.php b/modules/recaptchav2/ReCaptcha/RequestMethod/SocketPost.php new file mode 100644 index 000000000..45bee0e74 --- /dev/null +++ b/modules/recaptchav2/ReCaptcha/RequestMethod/SocketPost.php @@ -0,0 +1,121 @@ +socket = $socket; + } else { + $this->socket = new Socket(); + } + } + + /** + * Submit the POST request with the specified parameters. + * + * @param RequestParameters $params Request parameters + * @return string Body of the reCAPTCHA response + */ + public function submit(RequestParameters $params) + { + $errno = 0; + $errstr = ''; + + if (false === $this->socket->fsockopen('ssl://' . self::RECAPTCHA_HOST, 443, $errno, $errstr, 30)) { + return self::BAD_REQUEST; + } + + $content = $params->toQueryString(); + + $request = "POST " . self::SITE_VERIFY_PATH . " HTTP/1.1\r\n"; + $request .= "Host: " . self::RECAPTCHA_HOST . "\r\n"; + $request .= "Content-Type: application/x-www-form-urlencoded\r\n"; + $request .= "Content-length: " . strlen($content) . "\r\n"; + $request .= "Connection: close\r\n\r\n"; + $request .= $content . "\r\n\r\n"; + + $this->socket->fwrite($request); + $response = ''; + + while (!$this->socket->feof()) { + $response .= $this->socket->fgets(4096); + } + + $this->socket->fclose(); + + if (0 !== strpos($response, 'HTTP/1.1 200 OK')) { + return self::BAD_RESPONSE; + } + + $parts = preg_split("#\n\s*\n#Uis", $response); + + return $parts[1]; + } +} diff --git a/modules/recaptchav2/ReCaptcha/RequestParameters.php b/modules/recaptchav2/ReCaptcha/RequestParameters.php new file mode 100644 index 000000000..cb66f26cf --- /dev/null +++ b/modules/recaptchav2/ReCaptcha/RequestParameters.php @@ -0,0 +1,103 @@ +secret = $secret; + $this->response = $response; + $this->remoteIp = $remoteIp; + $this->version = $version; + } + + /** + * Array representation. + * + * @return array Array formatted parameters. + */ + public function toArray() + { + $params = array('secret' => $this->secret, 'response' => $this->response); + + if (!is_null($this->remoteIp)) { + $params['remoteip'] = $this->remoteIp; + } + + if (!is_null($this->version)) { + $params['version'] = $this->version; + } + + return $params; + } + + /** + * Query string representation for HTTP request. + * + * @return string Query string formatted parameters. + */ + public function toQueryString() + { + return http_build_query($this->toArray(), '', '&'); + } +} diff --git a/modules/recaptchav2/ReCaptcha/Response.php b/modules/recaptchav2/ReCaptcha/Response.php new file mode 100644 index 000000000..4d4d036d4 --- /dev/null +++ b/modules/recaptchav2/ReCaptcha/Response.php @@ -0,0 +1,122 @@ +success = $success; + $this->errorCodes = $errorCodes; + $this->hostname = $hostname; + } + + /** + * Is success? + * + * @return boolean + */ + public function isSuccess() + { + return $this->success; + } + + /** + * Get error codes. + * + * @return array + */ + public function getErrorCodes() + { + return $this->errorCodes; + } + + /** + * Get hostname. + * + * @return string + */ + public function getHostname() + { + return $this->hostname; + } +} diff --git a/modules/recaptchav2/autoload.php b/modules/recaptchav2/autoload.php new file mode 100644 index 000000000..5a7ee94c3 --- /dev/null +++ b/modules/recaptchav2/autoload.php @@ -0,0 +1,38 @@ + + + + 403 Forbidden + + + +

    Directory access is forbidden.

    + + + diff --git a/system/language/french/migration_lang.php b/system/language/french/migration_lang.php new file mode 100644 index 000000000..cdc8b5bca --- /dev/null +++ b/system/language/french/migration_lang.php @@ -0,0 +1,18 @@ + + + + 403 Forbidden + + + +

    Directory access is forbidden.

    + + + diff --git a/system/language/spanish/migration_lang.php b/system/language/spanish/migration_lang.php new file mode 100644 index 000000000..984eebb06 --- /dev/null +++ b/system/language/spanish/migration_lang.php @@ -0,0 +1,20 @@ +/css/bootstrap.min.css"> - - + + diff --git a/vendor/composer/ClassLoader.php b/vendor/composer/ClassLoader.php index 95f7e0978..fce8549f0 100644 --- a/vendor/composer/ClassLoader.php +++ b/vendor/composer/ClassLoader.php @@ -279,7 +279,7 @@ public function isClassMapAuthoritative() */ public function setApcuPrefix($apcuPrefix) { - $this->apcuPrefix = function_exists('apcu_fetch') && ini_get('apc.enabled') ? $apcuPrefix : null; + $this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null; } /** diff --git a/vendor/composer/autoload_psr4.php b/vendor/composer/autoload_psr4.php index 4f18a89b6..3351b4499 100644 --- a/vendor/composer/autoload_psr4.php +++ b/vendor/composer/autoload_psr4.php @@ -7,6 +7,7 @@ return array( 'Violet\\StreamingJsonEncoder\\' => array($vendorDir . '/violet/streaming-json-encoder/src'), + 'Slim\\Csrf\\' => array($vendorDir . '/slim/csrf/src'), 'Psr\\Log\\' => array($vendorDir . '/psr/log/Psr/Log'), 'Psr\\Http\\Message\\' => array($vendorDir . '/psr/http-message/src'), 'Mpdf\\' => array($vendorDir . '/mpdf/mpdf/src'), diff --git a/vendor/composer/autoload_static.php b/vendor/composer/autoload_static.php index 75ae4a42f..92344a209 100644 --- a/vendor/composer/autoload_static.php +++ b/vendor/composer/autoload_static.php @@ -15,6 +15,10 @@ class ComposerStaticInit4b9569c966d6a1d4516363e7ff8c8ece array ( 'Violet\\StreamingJsonEncoder\\' => 28, ), + 'S' => + array ( + 'Slim\\Csrf\\' => 10, + ), 'P' => array ( 'Psr\\Log\\' => 8, @@ -41,6 +45,10 @@ class ComposerStaticInit4b9569c966d6a1d4516363e7ff8c8ece array ( 0 => __DIR__ . '/..' . '/violet/streaming-json-encoder/src', ), + 'Slim\\Csrf\\' => + array ( + 0 => __DIR__ . '/..' . '/slim/csrf/src', + ), 'Psr\\Log\\' => array ( 0 => __DIR__ . '/..' . '/psr/log/Psr/Log', diff --git a/vendor/composer/installed.json b/vendor/composer/installed.json index 62d6bb99c..8f9b56eec 100644 --- a/vendor/composer/installed.json +++ b/vendor/composer/installed.json @@ -534,6 +534,58 @@ "pdf" ] }, + { + "name": "slim/csrf", + "version": "0.8.3", + "version_normalized": "0.8.3.0", + "source": { + "type": "git", + "url": "https://github.com/slimphp/Slim-Csrf.git", + "reference": "5f2bcf5d89adf86dc0455a32bea84d912ab466a7" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/slimphp/Slim-Csrf/zipball/5f2bcf5d89adf86dc0455a32bea84d912ab466a7", + "reference": "5f2bcf5d89adf86dc0455a32bea84d912ab466a7", + "shasum": "" + }, + "require": { + "paragonie/random_compat": "^1.1|^2.0|^9.99", + "php": ">=5.5.0", + "psr/http-message": "^1.0" + }, + "require-dev": { + "phpunit/phpunit": "^4.0", + "slim/slim": "~3.0" + }, + "time": "2018-08-22T16:12:18+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Slim\\Csrf\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Josh Lockhart", + "email": "hello@joshlockhart.com", + "homepage": "http://joshlockhart.com" + } + ], + "description": "Slim Framework 3 CSRF protection middleware", + "homepage": "http://slimframework.com", + "keywords": [ + "csrf", + "framework", + "middleware", + "slim" + ] + }, { "name": "violet/streaming-json-encoder", "version": "v1.1.1", diff --git a/vendor/slim/csrf/CHANGELOG.md b/vendor/slim/csrf/CHANGELOG.md new file mode 100644 index 000000000..c577ad7e2 --- /dev/null +++ b/vendor/slim/csrf/CHANGELOG.md @@ -0,0 +1,22 @@ +# Change Log + +## 2016-08-14 + +Now supports "persistence mode", to persist a single CSRF name/value pair throughout the life of a user's session. Added the following methods: + +- `protected getLastKeyPair` - gets the most recently generated key/value pair from storage. +- `protected loadLastKeyPair` - gets the most recently generated key/value pair from storage, and assign it to `$this->keyPair`. +- `public setPersistentTokenMode` +- `public getPersistentTokenMode` + +Note that if CSRF token validation fails, then the token should be renewed regardless of the persistence setting. + +The methods `getTokenName` and `getTokenValue` now return `null` if `$this->keyPair` has not yet been set. + +### Tests added: + +- `testPersistenceModeTrueBetweenRequestsArray` - Token should persist between requests after initial creation, when stored in an array. +- `testPersistenceModeTrueBetweenRequestsArrayAccess` - Token should persist between requests after initial creation, when stored in an ArrayObject. +- `testPersistenceModeFalseBetweenRequestsArray` - Token should be changed between requests, when stored in an array. +- `testPersistenceModeFalseBetweenRequestsArrayAccess` - Token should be changed between requests, when stored in an ArrayObject. +- `testUpdateAfterInvalidTokenWithPersistenceModeTrue` - New token should be generated after an invalid request, even if persistence mode is enabled. \ No newline at end of file diff --git a/modules/recaptcha/LICENSE b/vendor/slim/csrf/LICENSE.md similarity index 80% rename from modules/recaptcha/LICENSE rename to vendor/slim/csrf/LICENSE.md index b612f71f0..130902a4f 100644 --- a/modules/recaptcha/LICENSE +++ b/vendor/slim/csrf/LICENSE.md @@ -1,17 +1,14 @@ -Copyright (c) 2007 reCAPTCHA -- http://recaptcha.net -AUTHORS: - Mike Crawford - Ben Maurer +Copyright (c) 2012-2015 Josh Lockhart Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, diff --git a/vendor/slim/csrf/composer.json b/vendor/slim/csrf/composer.json new file mode 100644 index 000000000..e2a74b1a0 --- /dev/null +++ b/vendor/slim/csrf/composer.json @@ -0,0 +1,34 @@ +{ + "name": "slim/csrf", + "type": "library", + "description": "Slim Framework 3 CSRF protection middleware", + "keywords": ["slim","framework","middleware","csrf"], + "homepage": "http://slimframework.com", + "license": "MIT", + "authors": [ + { + "name": "Josh Lockhart", + "email": "hello@joshlockhart.com", + "homepage": "http://joshlockhart.com" + } + ], + "require": { + "php": ">=5.5.0", + "psr/http-message": "^1.0", + "paragonie/random_compat": "^1.1|^2.0|^9.99" + }, + "require-dev": { + "slim/slim": "~3.0", + "phpunit/phpunit": "^4.0" + }, + "autoload": { + "psr-4": { + "Slim\\Csrf\\": "src" + } + }, + "autoload-dev": { + "psr-4": { + "Slim\\Csrf\\Tests\\": "tests" + } + } +} diff --git a/vendor/slim/csrf/src/Guard.php b/vendor/slim/csrf/src/Guard.php new file mode 100644 index 000000000..43cb9a98b --- /dev/null +++ b/vendor/slim/csrf/src/Guard.php @@ -0,0 +1,474 @@ +prefix = rtrim($prefix, '_'); + if ($strength < 16) { + throw new RuntimeException('CSRF middleware failed. Minimum strength is 16.'); + } + $this->strength = $strength; + $this->storage = &$storage; + + $this->setFailureCallable($failureCallable); + $this->setStorageLimit($storageLimit); + + $this->setPersistentTokenMode($persistentTokenMode); + + $this->keyPair = null; + } + + /** + * Retrieve token name key + * + * @return string + */ + public function getTokenNameKey() + { + return $this->prefix . '_name'; + } + + /** + * Retrieve token value key + * + * @return string + */ + public function getTokenValueKey() + { + return $this->prefix . '_value'; + } + + /** + * Invoke middleware + * + * @param ServerRequestInterface $request PSR7 request object + * @param ResponseInterface $response PSR7 response object + * @param callable $next Next middleware callable + * + * @return ResponseInterface PSR7 response object + */ + public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) + { + $this->validateStorage(); + + // Validate POST, PUT, DELETE, PATCH requests + if (in_array($request->getMethod(), ['POST', 'PUT', 'DELETE', 'PATCH'])) { + $body = $request->getParsedBody(); + $body = $body ? (array)$body : []; + $name = isset($body[$this->prefix . '_name']) ? $body[$this->prefix . '_name'] : false; + $value = isset($body[$this->prefix . '_value']) ? $body[$this->prefix . '_value'] : false; + if (!$name || !$value || !$this->validateToken($name, $value)) { + // Need to regenerate a new token, as the validateToken removed the current one. + $request = $this->generateNewToken($request); + + $failureCallable = $this->getFailureCallable(); + return $failureCallable($request, $response, $next); + } + } + + // Generate new CSRF token if persistentTokenMode is false, or if a valid keyPair has not yet been stored + if (!$this->persistentTokenMode || !$this->loadLastKeyPair()) { + $request = $this->generateNewToken($request); + } elseif ($this->persistentTokenMode) { + $pair = $this->loadLastKeyPair() ? $this->keyPair : $this->generateToken(); + $request = $this->attachRequestAttributes($request, $pair); + } + + // Enforce the storage limit + $this->enforceStorageLimit(); + + return $next($request, $response); + } + + /** + * @param $prefix + * @param $storage + * @return mixed + */ + public function validateStorage() + { + if (is_array($this->storage)) { + return $this->storage; + } + + if ($this->storage instanceof ArrayAccess) { + return $this->storage; + } + + if (!isset($_SESSION)) { + throw new RuntimeException('CSRF middleware failed. Session not found.'); + } + if (!array_key_exists($this->prefix, $_SESSION)) { + $_SESSION[$this->prefix] = []; + } + $this->storage = &$_SESSION[$this->prefix]; + return $this->storage; + } + + /** + * Generates a new CSRF token + * + * @return array + */ + public function generateToken() + { + // Generate new CSRF token + $name = uniqid($this->prefix); + $value = $this->createToken(); + $this->saveToStorage($name, $value); + + $this->keyPair = [ + $this->prefix . '_name' => $name, + $this->prefix . '_value' => $value + ]; + + return $this->keyPair; + } + + /** + * Generates a new CSRF token and attaches it to the Request Object + * + * @param ServerRequestInterface $request PSR7 response object. + * + * @return ServerRequestInterface PSR7 response object. + */ + public function generateNewToken(ServerRequestInterface $request) + { + + $pair = $this->generateToken(); + + $request = $this->attachRequestAttributes($request, $pair); + + return $request; + } + + /** + * Validate CSRF token from current request + * against token value stored in $_SESSION + * + * @param string $name CSRF name + * @param string $value CSRF token value + * + * @return bool + */ + public function validateToken($name, $value) + { + $token = $this->getFromStorage($name); + if (function_exists('hash_equals')) { + $result = ($token !== false && hash_equals($token, $value)); + } else { + $result = ($token !== false && $token === $value); + } + + // If we're not in persistent token mode, delete the token. + if (!$this->persistentTokenMode) { + $this->removeFromStorage($name); + } + + return $result; + } + + /** + * Create CSRF token value + * + * @return string + */ + protected function createToken() + { + return bin2hex(random_bytes($this->strength)); + } + + /** + * Save token to storage + * + * @param string $name CSRF token name + * @param string $value CSRF token value + */ + protected function saveToStorage($name, $value) + { + $this->storage[$name] = $value; + } + + /** + * Get token from storage + * + * @param string $name CSRF token name + * + * @return string|bool CSRF token value or `false` if not present + */ + protected function getFromStorage($name) + { + return isset($this->storage[$name]) ? $this->storage[$name] : false; + } + + /** + * Get the most recent key pair from storage. + * + * @return string[]|null Array containing name and value if found, null otherwise + */ + protected function getLastKeyPair() + { + // Use count, since empty ArrayAccess objects can still return false for `empty` + if (count($this->storage) < 1) { + return null; + } + + foreach ($this->storage as $name => $value) { + continue; + } + + $keyPair = [ + $this->prefix . '_name' => $name, + $this->prefix . '_value' => $value + ]; + + return $keyPair; + } + + /** + * Load the most recent key pair in storage. + * + * @return bool `true` if there was a key pair to load in storage, false otherwise. + */ + protected function loadLastKeyPair() + { + $this->keyPair = $this->getLastKeyPair(); + + if ($this->keyPair) { + return true; + } + + return false; + } + + /** + * Remove token from storage + * + * @param string $name CSRF token name + */ + protected function removeFromStorage($name) + { + $this->storage[$name] = ' '; + unset($this->storage[$name]); + } + + /** + * Remove the oldest tokens from the storage array so that there + * are never more than storageLimit tokens in the array. + * + * This is required as a token is generated every request and so + * most will never be used. + */ + protected function enforceStorageLimit() + { + if ($this->storageLimit < 1) { + return; + } + + // $storage must be an array or implement Countable and Traversable + if (!is_array($this->storage) + && !($this->storage instanceof Countable && $this->storage instanceof Traversable) + ) { + return; + } + + if (is_array($this->storage)) { + while (count($this->storage) > $this->storageLimit) { + array_shift($this->storage); + } + } else { + // array_shift() doesn't work for ArrayAccess, so we need an iterator in order to use rewind() + // and key(), so that we can then unset + $iterator = $this->storage; + if ($this->storage instanceof \IteratorAggregate) { + $iterator = $this->storage->getIterator(); + } + while (count($this->storage) > $this->storageLimit) { + $iterator->rewind(); + unset($this->storage[$iterator->key()]); + } + } + } + + /** + * @param ServerRequestInterface $request + * @param $pair + * @return static + */ + protected function attachRequestAttributes(ServerRequestInterface $request, $pair) + { + return $request->withAttribute($this->prefix . '_name', $pair[$this->prefix . '_name']) + ->withAttribute($this->prefix . '_value', $pair[$this->prefix . '_value']); + } + + /** + * Getter for failureCallable + * + * @return callable|\Closure + */ + public function getFailureCallable() + { + if (is_null($this->failureCallable)) { + $this->failureCallable = function (ServerRequestInterface $request, ResponseInterface $response, $next) { + $body = new \Slim\Http\Body(fopen('php://temp', 'r+')); + $body->write('Failed CSRF check!'); + return $response->withStatus(400)->withHeader('Content-type', 'text/plain')->withBody($body); + }; + } + return $this->failureCallable; + } + + /** + * Setter for failureCallable + * + * @param mixed $failureCallable Value to set + * @return $this + */ + public function setFailureCallable($failureCallable) + { + $this->failureCallable = $failureCallable; + return $this; + } + + /** + * Setter for persistentTokenMode + * + * @param bool $persistentTokenMode True to use the same token throughout the session (unless there is a validation error), + * false to get a new token with each request. + * @return $this + */ + public function setPersistentTokenMode($persistentTokenMode) + { + $this->persistentTokenMode = $persistentTokenMode; + return $this; + } + + /** + * Setter for storageLimit + * + * @param integer $storageLimit Value to set + * @return $this + */ + public function setStorageLimit($storageLimit) + { + $this->storageLimit = (int)$storageLimit; + return $this; + } + + /** + * Getter for persistentTokenMode + * + * @return bool + */ + public function getPersistentTokenMode() + { + return $this->persistentTokenMode; + } + + /** + * @return string + */ + public function getTokenName() + { + return isset($this->keyPair[$this->getTokenNameKey()]) ? $this->keyPair[$this->getTokenNameKey()] : null; + } + + /** + * @return string + */ + public function getTokenValue() + { + return isset($this->keyPair[$this->getTokenValueKey()]) ? $this->keyPair[$this->getTokenValueKey()] : null; + } +}