From 87e11dc642f6134a4e682bac9f8bd53ce328d424 Mon Sep 17 00:00:00 2001 From: HungNA - Technical Manager Date: Fri, 12 Apr 2024 15:54:03 +0700 Subject: [PATCH] Fomat Code Style implement PSR12 --- README.md | 110 +- composer.json | 190 +- helpers/alphaid_helper.php | 232 +-- helpers/array_helper.php | 914 ++++----- helpers/assets_helper.php | 754 ++++---- helpers/blogspot_helper.php | 94 +- helpers/byte_helper.php | 60 +- helpers/chart_render.php | 20 +- helpers/common_helper.php | 252 +-- helpers/database_helper.php | 66 +- helpers/date_helper.php | 216 +-- helpers/debug_helper.php | 48 +- helpers/download_helper.php | 144 +- helpers/env_helper.php | 64 +- helpers/escape_helper.php | 22 +- helpers/facebook_helper.php | 206 +- helpers/file_helper.php | 776 ++++---- helpers/form_helper.php | 44 +- helpers/gravatar_helper.php | 90 +- helpers/html_helper.php | 466 ++--- helpers/image_helper.php | 268 +-- helpers/index.html | 2 +- helpers/ip_helper.php | 468 ++--- helpers/japan_helper.php | 10 +- helpers/meta_helper.php | 58 +- helpers/money_helper.php | 28 +- helpers/nanoid_helper.php | 40 +- helpers/number_helper.php | 166 +- helpers/paging_helper.php | 432 ++--- helpers/placeholder_helper.php | 68 +- helpers/request_helper.php | 292 +-- helpers/security_helper.php | 300 +-- helpers/sentry_helper.php | 80 +- helpers/string_helper.php | 1182 ++++++------ helpers/text_helper.php | 1658 ++++++++-------- helpers/tinyurl_helper.php | 30 +- helpers/url_helper.php | 3094 +++++++++++++++--------------- helpers/uuid_helper.php | 226 +-- helpers/video_embed_helper.php | 190 +- helpers/vn_province_helper.php | 138 +- helpers/xml_helper.php | 334 ++-- src/BaseHelper.php | 94 +- src/BasicCurl.php | 1638 ++++++++-------- src/BasicImageHelperWithGD.php | 152 +- src/ChartRender.php | 24 +- src/Favicon.php | 80 +- src/HelperException.php | 22 +- src/ImageHelper.php | 72 +- src/JapanUtils.php | 24 +- src/ServerReport.php | 100 +- src/SimpleCurl.php | 644 +++---- src/SimpleElasticsearch.php | 1016 +++++----- src/SimpleParseOpenGraph.php | 456 ++--- src/SimpleRequests.php | 438 ++--- src/SimpleRestful.php | 102 +- src/SimpleVerifiedKey.php | 40 +- src/SimpleVisitor.php | 244 +-- src/Valid.php | 1138 +++++------ src/Validator.php | 3306 ++++++++++++++++---------------- src/index.html | 2 +- src/japan/pref_code.php | 94 +- src/validator/lang/ar.php | 49 +- src/validator/lang/az.php | 61 +- src/validator/lang/bg.php | 60 +- src/validator/lang/de.php | 58 +- src/validator/lang/el.php | 60 +- src/validator/lang/en.php | 74 +- src/validator/lang/es.php | 64 +- src/validator/lang/fa.php | 74 +- src/validator/lang/fi.php | 61 +- src/validator/lang/fr.php | 74 +- src/validator/lang/id.php | 58 +- src/validator/lang/it.php | 60 +- src/validator/lang/ja.php | 74 +- src/validator/lang/ko.php | 60 +- src/validator/lang/lt.php | 67 +- src/validator/lang/lv.php | 54 +- src/validator/lang/nb.php | 69 +- src/validator/lang/nl.php | 60 +- src/validator/lang/nn.php | 60 +- src/validator/lang/pl.php | 60 +- src/validator/lang/pt-br.php | 64 +- src/validator/lang/ro.php | 60 +- src/validator/lang/ru.php | 68 +- src/validator/lang/sk.php | 60 +- src/validator/lang/sl.php | 74 +- src/validator/lang/sv.php | 62 +- src/validator/lang/th.php | 60 +- src/validator/lang/tr.php | 60 +- src/validator/lang/uk.php | 58 +- src/validator/lang/vi.php | 60 +- src/validator/lang/zh-cn.php | 66 +- src/validator/lang/zh-tw.php | 72 +- 93 files changed, 12792 insertions(+), 12747 deletions(-) diff --git a/README.md b/README.md index 4af7536..7647834 100644 --- a/README.md +++ b/README.md @@ -6,9 +6,11 @@ 1 vài helper cơ bản khi sử dụng với CodeIgniter 3. -Có thể đưa vào nhiều bộ code hay framework khác, tuy nhiên có 1 số function require framework `CodeIgniter`, tuy nhiên không ảnh hưởng tới hiệu suất sử dụng +Có thể đưa vào nhiều bộ code hay framework khác, tuy nhiên có 1 số function require framework `CodeIgniter`, tuy nhiên +không ảnh hưởng tới hiệu suất sử dụng -Trong trường hợp tích hợp gói này vào các framework, source khác ngoài `CodeIgniter`, bạn cần cài kèm thêm gói `nguyenanhung/polyfill-codeigniter-built-in` để sử dụng tốt nhất +Trong trường hợp tích hợp gói này vào các framework, source khác ngoài `CodeIgniter`, bạn cần cài kèm thêm +gói `nguyenanhung/polyfill-codeigniter-built-in` để sử dụng tốt nhất 1 vài framework tôi cũng thường dùng với gói này là @@ -88,23 +90,40 @@ Dưới đây là danh sách các Helper được hỗ trợ trong bộ thư vi ### Assets Helper -- [x] Helper Function: `assets_url` - Hàm lấy ra Assets Url, điều kiện tồn tại thư mục `assets` trong thư mục `public/`. Trong trường hợp trong file `config.php` tồn tại biến `assets_version` sẽ tự động thêm version vào đằng sau các file CSS, JS -- [x] Helper Function: `static_url` - Hàm lấy ra Static Resource Url, điều kiện tồn tại cấu hình `config_item('static_url')` trong config của website. Trong trường hợp trong file `config.php` tồn tại biến `assets_version` sẽ tự động thêm version vào +- [x] Helper Function: `assets_url` - Hàm lấy ra Assets Url, điều kiện tồn tại thư mục `assets` trong thư mục `public/`. + Trong trường hợp trong file `config.php` tồn tại biến `assets_version` sẽ tự động thêm version vào đằng sau các file + CSS, JS +- [x] Helper Function: `static_url` - Hàm lấy ra Static Resource Url, điều kiện tồn tại cấu + hình `config_item('static_url')` trong config của website. Trong trường hợp trong file `config.php` tồn tại + biến `assets_version` sẽ tự động thêm version vào đằng sau các file CSS, JS -- [x] Helper Function: `templates_url` - Hàm lấy ra Assets Url, điều kiện tồn tại thư mục `templates` trong thư mục `public/`. Trong trường hợp trong file `config.php` tồn tại biến `assets_version` sẽ tự động thêm version vào đằng sau các file CSS, +- [x] Helper Function: `templates_url` - Hàm lấy ra Assets Url, điều kiện tồn tại thư mục `templates` trong thư + mục `public/`. Trong trường hợp trong file `config.php` tồn tại biến `assets_version` sẽ tự động thêm version vào đằng + sau các file CSS, JS -- [x] Helper Function: `editor_url` - Hàm lấy ra Assets Url, điều kiện tồn tại thư mục `assets/editors/` trong thư mục `public/`. Trong trường hợp trong file `config.php` tồn tại biến `assets_version` sẽ tự động thêm version vào đằng sau các file +- [x] Helper Function: `editor_url` - Hàm lấy ra Assets Url, điều kiện tồn tại thư mục `assets/editors/` trong thư + mục `public/`. Trong trường hợp trong file `config.php` tồn tại biến `assets_version` sẽ tự động thêm version vào đằng + sau các file CSS, JS -- [x] Helper Function: `favicon_url`- Hàm lấy ra Assets Url, điều kiện tồn tại thư mục `assets/favicon/` trong thư mục `public/`. Trong trường hợp trong file `config.php` tồn tại biến `assets_version` sẽ tự động thêm version vào đằng sau các file +- [x] Helper Function: `favicon_url`- Hàm lấy ra Assets Url, điều kiện tồn tại thư mục `assets/favicon/` trong thư + mục `public/`. Trong trường hợp trong file `config.php` tồn tại biến `assets_version` sẽ tự động thêm version vào đằng + sau các file CSS, JS - [x] Helper Function: `favicon_html_tag`- Hàm lấy ra đoạn HTML thể hiện Favicon dựa vào URL folder favicon đầu vào -- [x] Helper Function: `storage_url` - Need config `storage_url` item in config.php file. VD: `$config['storage_url'] = 'https://storage.nguyenanhung.com/';` -- [x] Helper Function: `go_url` - Need config `go_url` item in `config.php` file. VD: `$config['go_url'] = 'https://go.nguyenanhung.com/';` -- [x] Helper Function: `assets_mobile` - Lấy ra đường dẫn assets của giao diện mobile (thực tế ít dùng, duy trì cho các dự án cũ) -- [x] Helper Function: `assets_themes` - Lấy ra đường dẫn assets của giao diện pc (thực tế ít dùng, duy trì cho các dự án cũ) -- [x] Helper Function: `assets_themes_dashboard` - Lấy ra đường dẫn assets của giao diện dashboard (thực tế ít dùng, duy trì cho các dự án cũ) -- [x] Helper Function: `assets_themes_comingsoon` - Lấy ra đường dẫn assets của giao diện coming soon (thực tế ít dùng, duy trì cho các dự án cũ) -- [x] Helper Function: `assets_themes_error` - Lấy ra đường dẫn assets của giao diện error (thực tế ít dùng, duy trì cho các dự án cũ) +- [x] Helper Function: `storage_url` - Need config `storage_url` item in config.php file. + VD: `$config['storage_url'] = 'https://storage.nguyenanhung.com/';` +- [x] Helper Function: `go_url` - Need config `go_url` item in `config.php` file. + VD: `$config['go_url'] = 'https://go.nguyenanhung.com/';` +- [x] Helper Function: `assets_mobile` - Lấy ra đường dẫn assets của giao diện mobile (thực tế ít dùng, duy trì cho các + dự án cũ) +- [x] Helper Function: `assets_themes` - Lấy ra đường dẫn assets của giao diện pc (thực tế ít dùng, duy trì cho các dự + án cũ) +- [x] Helper Function: `assets_themes_dashboard` - Lấy ra đường dẫn assets của giao diện dashboard (thực tế ít dùng, duy + trì cho các dự án cũ) +- [x] Helper Function: `assets_themes_comingsoon` - Lấy ra đường dẫn assets của giao diện coming soon (thực tế ít dùng, + duy trì cho các dự án cũ) +- [x] Helper Function: `assets_themes_error` - Lấy ra đường dẫn assets của giao diện error (thực tế ít dùng, duy trì cho + các dự án cũ) - [x] Helper Function: `cdn_js_url` - Resource JS, CSS từ CDN của Cloudflare - [x] Helper Function: `google_fonts_url` - Resource Google Font - [x] Helper Function: `bootstrapcdn_url` - Resource CDN từ Bootstrap @@ -133,7 +152,8 @@ Dưới đây là danh sách các Helper được hỗ trợ trong bộ thư vi ### Database Helper -- [x] Helper Function: `generate_list_id_with_parent_id ` - Tạo 1 list các ID, trong đó chứa các tập con phụ thuộc của ID đó. VD: Dùng trong trường hợp muốn hiển thị nội dung của category cha và các category con trong cùng 1 page content +- [x] Helper Function: `generate_list_id_with_parent_id ` - Tạo 1 list các ID, trong đó chứa các tập con phụ thuộc của + ID đó. VD: Dùng trong trường hợp muốn hiển thị nội dung của category cha và các category con trong cùng 1 page content ### Date Helper @@ -164,7 +184,8 @@ Các hàm này dùng debug ### Facebook Helper - [x] Helper Function: `widget_facebook_div_init` - Hàm tạo ra `
` -- [x] Helper Function: `widget_facebook_script_init` - Hạm tạo ra đoạn script init trong trường hợp cần nhúng JS Facebook +- [x] Helper Function: `widget_facebook_script_init` - Hạm tạo ra đoạn script init trong trường hợp cần nhúng JS + Facebook - [x] Helper Function: `widget_facebook_comments` - Hàm tạo ra khung comment facebook - [x] Helper Function: `widget_facebook_share_button` - Hàm tạo ra nút share facebook - [x] Helper Function: `widget_facebook_like_button` - Hàm tạo ra nút like facebook @@ -176,7 +197,8 @@ Các hàm này dùng debug - [x] Helper Function: `genarateFileIndex` - Tự động tạo nội dung file `index.html` - [x] Helper Function: `genarateFileHtaccess` - Tự động tạo nội dung file `.htaccess` - [x] Helper Function: `genarateFileReadme` - Tự động tạo nội dung file `README.md` -- [x] Helper Function: `makeNewFolder` - Hàm tạo 1 thư mục mới và genre sẵn trong đó 3 file: `README.md`, `index.html`, `.htaccess` +- [x] Helper Function: `makeNewFolder` - Hàm tạo 1 thư mục mới và genre sẵn trong đó 3 file: `README.md`, `index.html` + , `.htaccess` - [x] Helper Function: `new_folder` - Chức năng tương tự với hàm `makeNewFolder` - [x] Helper Function: `scan_folder` - Quét và lấy ra danh sách các thông tin dữ liệu trong folder - [x] Helper Function: `getAllFileSizeInFolder` - Get all File size in Folder @@ -204,16 +226,19 @@ Các hàm này dùng debug ### Image Helper - [x] Helper Function: `google_image_resize` - Resize Image sử dụng Google Gadget Proxy -- [x] Helper Function: `google_image_proxy_dns_prefetch` - Hàm cung cấp DNS Prefetch trong trường hợp sử dụng `google_image_resize` +- [x] Helper Function: `google_image_proxy_dns_prefetch` - Hàm cung cấp DNS Prefetch trong trường hợp sử + dụng `google_image_resize` - [x] Helper Function: `wordpress_proxy` - Resize & Cache Image sử dụng WordPress Proxy -- [x] Helper Function: `wordpress_proxy_dns_prefetch` - Hàm cung cấp DNS Prefetch trong trường hợp sử dụng `wordpress_proxy` +- [x] Helper Function: `wordpress_proxy_dns_prefetch` - Hàm cung cấp DNS Prefetch trong trường hợp sử + dụng `wordpress_proxy` - [x] Helper Function: `bear_framework_image_url` - Hàm format Image Url - dành riêng cho BEAR framework - [x] Helper Function: `create_image_thumbnail` - Hàm create thumbnail - dành riêng cho BEAR framework ### IP Helper - [x] Helper Function: `getIPAddress` - Hàm lấy ra địa chỉ IP thực tế của người dùng -- [x] Helper Function: `getIPAddressByHaProxy` - Hàm lấy ra địa chỉ IP thực tế của người dùng nhưng ở server có chạy Ha Proxy, thông qua biến `HTTP_X_FORWARDED_FOR` +- [x] Helper Function: `getIPAddressByHaProxy` - Hàm lấy ra địa chỉ IP thực tế của người dùng nhưng ở server có chạy Ha + Proxy, thông qua biến `HTTP_X_FORWARDED_FOR` - [x] Helper Function: `validateIP` - Hàm validate 1 string có phải IP ko. TRUE nếu đó là IP - [x] Helper Function: `validateIPV4` - Hàm validate 1 string có phải IP v4 ko. TRUE nếu đó là IP - [x] Helper Function: `validateIPV6` - Hàm validate 1 string có phải IP v6 ko. TRUE nếu đó là IP @@ -221,7 +246,8 @@ Các hàm này dùng debug ### Meta Helper -- [x] Helper Function: `setupMetaDnsPrefetch` - Hàm hỗ trợ gen ra 1 đoạn HTML Dns Prefetch tương tự `` +- [x] Helper Function: `setupMetaDnsPrefetch` - Hàm hỗ trợ gen ra 1 đoạn HTML Dns Prefetch tương + tự `` ### Money Helper @@ -233,13 +259,15 @@ Helper này sử dụng gói `hidehalo/nanoid-php` để gen ra 1 mã random Id Hiện tại việc sử dụng nanoid đang là xu hướng so với uuid truyền thống -Để sử dụng được gói này, cần cài packages `nguyenanhung/nanoid-helper` bằng lệnh `composer require nguyenanhung/nanoid-helper` +Để sử dụng được gói này, cần cài packages `nguyenanhung/nanoid-helper` bằng +lệnh `composer require nguyenanhung/nanoid-helper` - [x] Helper Function: `randomNanoId` ### Number Helper -- [x] Helper Function: `convertNumberToWords` - Tác dụng convert 1 số thành chữ, ví dụ `123` thành `One Hundred Twenty Three` +- [x] Helper Function: `convertNumberToWords` - Tác dụng convert 1 số thành chữ, ví dụ `123` + thành `One Hundred Twenty Three` ### Paging Helper @@ -258,12 +286,14 @@ Hiện tại việc sử dụng nanoid đang là xu hướng so với uuid truy - [x] Helper Function: `sendSimpleGetRequest` - Tiến hành thực thi 1 request đơn giản sử dụng CURL với phương thức GET - [x] Helper Function: `sendSimpleRestfulExecuteRequest` - Thực thi 1 simple request tới Restful API sử dụng CURL -- [x] Helper Function: `bear_post_async_request` - Make an asynchronous POST request - Thực hiện yêu cầu POST không đồng bộ trong nội bộ site mà không cần chờ phản hồi => Không ảnh hưởng, không trì hoãn tiến trình đang chạy +- [x] Helper Function: `bear_post_async_request` - Make an asynchronous POST request - Thực hiện yêu cầu POST không đồng + bộ trong nội bộ site mà không cần chờ phản hồi => Không ảnh hưởng, không trì hoãn tiến trình đang chạy - [x] Helper Function: `get_http_response_code` - Get HTTP Response Code with `get_headers` ### Security Helper -- [x] Helper Function: `xssValidation` - Validation dữ liệu đầu vào có bị dính lỗi XSS hay không. Hàm này không có tác dụng escape, nếu muốn, hãy cài thêm packages `nguyenanhung/security` +- [x] Helper Function: `xssValidation` - Validation dữ liệu đầu vào có bị dính lỗi XSS hay không. Hàm này không có tác + dụng escape, nếu muốn, hãy cài thêm packages `nguyenanhung/security` ### Sentry Helper @@ -278,15 +308,19 @@ Hiện tại việc sử dụng nanoid đang là xu hướng so với uuid truy - [x] Helper Function: `str_after` - Return the part of a string after a given value. - [x] Helper Function: `str_before` - Get the part of a string before a given value. - [x] Helper Function: `str_limit_words` - Limit the number of words in a string. Put value of $end to the string end. -- [x] Helper Function: `str_limit_characters` - Limit the number of characters in a string. Put value of $end to the string end. +- [x] Helper Function: `str_limit_characters` - Limit the number of characters in a string. Put value of $end to the + string end. - [x] Helper Function: `str_contains` - Tests if a string contains a given element - [x] Helper Function: `str_ignore_contains` - Tests if a string contains a given element. Ignore case sensitivity. - [x] Helper Function: `str_starts_with` - Determine if a given string starts with a given substring. -- [x] Helper Function: `str_ignore_starts_with` - Determine if a given string starts with a given substring. Ignore case sensitivity. +- [x] Helper Function: `str_ignore_starts_with` - Determine if a given string starts with a given substring. Ignore case + sensitivity. - [x] Helper Function: `str_ends_with` - Determine if a given string ends with a given substring. -- [x] Helper Function: `str_ignore_ends_with` - Determine if a given string ends with a given substring. Ignore case sensitivity. +- [x] Helper Function: `str_ignore_ends_with` - Determine if a given string ends with a given substring. Ignore case + sensitivity. - [x] Helper Function: `str_after_last` - Return the part of a string after the last occurrence of a given search value. -- [x] Helper Function: `hide_characters` - Convert `nguyenanhung` to `ngxyexanxunx`, acts as a very simple and predictable character encoding function but is necessary to hide something simple +- [x] Helper Function: `hide_characters` - Convert `nguyenanhung` to `ngxyexanxunx`, acts as a very simple and + predictable character encoding function but is necessary to hide something simple ### Text Helper @@ -324,7 +358,8 @@ Hiện tại việc sử dụng nanoid đang là xu hướng so với uuid truy - [x] Helper Function: `images_url` - Hàm customize dành riêng cho framework CodeIgniter - [x] Helper Function: `audio_url` - Hàm customize dành riêng cho framework CodeIgniter - [x] Helper Function: `append_params_into_url` - Append parameters to URL -- [x] Helper Function: `append_query_string_to_current_url` - Get current URL including query string - Hàm customize dành riêng cho framework CodeIgniter +- [x] Helper Function: `append_query_string_to_current_url` - Get current URL including query string - Hàm customize + dành riêng cho framework CodeIgniter ### UUID Helper @@ -336,10 +371,14 @@ Hiện tại việc sử dụng nanoid đang là xu hướng so với uuid truy ### Video Embed Helper -- [x] Helper Function: `convert_video_embed_vimeo` - Convert Video URL to Embed Vimeo (ít dùng, lưu tại đây vì còn nhiều project cũ đang sử dụng) -- [x] Helper Function: `convert_video_embed_dailymotion` - Convert Video URL to Embed DailyMotion (ít dùng, lưu tại đây vì còn nhiều project cũ đang sử dụng) -- [x] Helper Function: `convert_video_embed_youtube` - Convert Video URL to Embed YouTube (ít dùng, lưu tại đây vì còn nhiều project cũ đang sử dụng) -- [x] Helper Function: `convert_video_v_embed_youtube` - Convert Video URL to Embed YouTube (ít dùng, lưu tại đây vì còn nhiều project cũ đang sử dụng) +- [x] Helper Function: `convert_video_embed_vimeo` - Convert Video URL to Embed Vimeo (ít dùng, lưu tại đây vì còn nhiều + project cũ đang sử dụng) +- [x] Helper Function: `convert_video_embed_dailymotion` - Convert Video URL to Embed DailyMotion (ít dùng, lưu tại đây + vì còn nhiều project cũ đang sử dụng) +- [x] Helper Function: `convert_video_embed_youtube` - Convert Video URL to Embed YouTube (ít dùng, lưu tại đây vì còn + nhiều project cũ đang sử dụng) +- [x] Helper Function: `convert_video_v_embed_youtube` - Convert Video URL to Embed YouTube (ít dùng, lưu tại đây vì còn + nhiều project cũ đang sử dụng) - [x] Helper Function: `youtube_image_thumbnail` - Convert YoutubeID to Youtube Thumbnail URL ### XML Helper @@ -382,7 +421,8 @@ Class cung cấp 1 số phương thức giúp xử lý hình ảnh - [x] Method `wordpressProxy` - Tạo URL Resize sử dụng WordPress Proxy - [x] Method `wordpressProxyDnsPrefetch` - Setup DNS Prefetch cho WordPress Proxy, nhằm tăng tốc độ truy vấn - [x] Method `createThumbnail` - Hàm tạo Thumbnail, để sử dụng cần cài thêm gói `nguyenanhung/image` -- [x] Method `createThumbnailWithCodeIgniterCache` - Hàm tạo Thumbnail kết hợp thư viện Cache của CodeIgniter, để sử dụng cần cài thêm gói `nguyenanhung/image` +- [x] Method `createThumbnailWithCodeIgniterCache` - Hàm tạo Thumbnail kết hợp thư viện Cache của CodeIgniter, để sử + dụng cần cài thêm gói `nguyenanhung/image` ## Maintainer & Supporter diff --git a/composer.json b/composer.json index cb18d4e..c0e64bd 100644 --- a/composer.json +++ b/composer.json @@ -1,97 +1,97 @@ { - "name": "nguyenanhung/codeigniter-basic-helper", - "type": "library", - "description": "CodeIgniter - Basic Helper", - "keywords": [ - "php", - "codeigniter", - "codeigniter3", - "codeigniter-helper", - "codeigniter-library", - "codeigniter-startapp", - "helper", - "library" - ], - "homepage": "https://github.com/nguyenanhung/codeigniter-basic-helper", - "license": "GPL-3.0", - "authors": [ - { - "name": "Nguyen An Hung", - "email": "dev@nguyenanhung.com", - "homepage": "https://nguyenanhung.com", - "role": "Developer" - } - ], - "require": { - "php": ">=5.6", - "ext-curl": "*", - "ext-json": "*", - "ext-mbstring": "*", - "nguyenanhung/html-helper": "^2.0 || ^1.0", - "nguyenanhung/mobile-helper": "^2.0 || ^1.0", - "nguyenanhung/image-helper": "^2.0 || ^1.0", - "nguyenanhung/basic-miscellaneous-helper": "^2.0 || ^1.0" - }, - "require-dev": { - "nguyenanhung/my-debug": "^4.0 || ^3.0 || ^2.0", - "nguyenanhung/nanoid-helper": "^2.0 || ^1.0", - "nguyenanhung/json-helper": "^2.0 || ^1.0", - "nguyenanhung/image": "^3.0 || ^2.0 || ^1.0", - "nguyenanhung/codeigniter-framework": ">= 3.1" - }, - "autoload": { - "psr-4": { - "nguyenanhung\\CodeIgniter\\BasicHelper\\": "src/" - }, - "files": [ - "helpers/alphaid_helper.php", - "helpers/array_helper.php", - "helpers/assets_helper.php", - "helpers/blogspot_helper.php", - "helpers/byte_helper.php", - "helpers/chart_render.php", - "helpers/common_helper.php", - "helpers/database_helper.php", - "helpers/date_helper.php", - "helpers/debug_helper.php", - "helpers/download_helper.php", - "helpers/env_helper.php", - "helpers/escape_helper.php", - "helpers/facebook_helper.php", - "helpers/file_helper.php", - "helpers/form_helper.php", - "helpers/gravatar_helper.php", - "helpers/html_helper.php", - "helpers/image_helper.php", - "helpers/ip_helper.php", - "helpers/meta_helper.php", - "helpers/japan_helper.php", - "helpers/money_helper.php", - "helpers/nanoid_helper.php", - "helpers/number_helper.php", - "helpers/paging_helper.php", - "helpers/placeholder_helper.php", - "helpers/request_helper.php", - "helpers/security_helper.php", - "helpers/sentry_helper.php", - "helpers/string_helper.php", - "helpers/text_helper.php", - "helpers/tinyurl_helper.php", - "helpers/url_helper.php", - "helpers/uuid_helper.php", - "helpers/video_embed_helper.php", - "helpers/vn_province_helper.php", - "helpers/xml_helper.php" - ] - }, - "suggest": { - "ext-curl": "Need support CURL", - "ext-json": "Need support JSON", - "nguyenanhung/helpers": "Awesome Helpers - Powerful Library, Helpers and Tools", - "nguyenanhung/image": "Need support for Image Service", - "nguyenanhung/nanoid-helper": "Need support for helper function randomNanoId()", - "nguyenanhung/json-helper": "Need support for JSON", - "nguyenanhung/mobile-helper": "Need support for Mobile Support", - "sentry/sdk": "Need support for Logging with Sentry" - } + "name": "nguyenanhung/codeigniter-basic-helper", + "type": "library", + "description": "CodeIgniter - Basic Helper", + "keywords": [ + "php", + "codeigniter", + "codeigniter3", + "codeigniter-helper", + "codeigniter-library", + "codeigniter-startapp", + "helper", + "library" + ], + "homepage": "https://github.com/nguyenanhung/codeigniter-basic-helper", + "license": "GPL-3.0", + "authors": [ + { + "name": "Nguyen An Hung", + "email": "dev@nguyenanhung.com", + "homepage": "https://nguyenanhung.com", + "role": "Developer" + } + ], + "require": { + "php": ">=5.6", + "ext-curl": "*", + "ext-json": "*", + "ext-mbstring": "*", + "nguyenanhung/html-helper": "^2.0 || ^1.0", + "nguyenanhung/mobile-helper": "^2.0 || ^1.0", + "nguyenanhung/image-helper": "^2.0 || ^1.0", + "nguyenanhung/basic-miscellaneous-helper": "^2.0 || ^1.0" + }, + "require-dev": { + "nguyenanhung/my-debug": "^4.0 || ^3.0 || ^2.0", + "nguyenanhung/nanoid-helper": "^2.0 || ^1.0", + "nguyenanhung/json-helper": "^2.0 || ^1.0", + "nguyenanhung/image": "^3.0 || ^2.0 || ^1.0", + "nguyenanhung/codeigniter-framework": ">= 3.1" + }, + "autoload": { + "psr-4": { + "nguyenanhung\\CodeIgniter\\BasicHelper\\": "src/" + }, + "files": [ + "helpers/alphaid_helper.php", + "helpers/array_helper.php", + "helpers/assets_helper.php", + "helpers/blogspot_helper.php", + "helpers/byte_helper.php", + "helpers/chart_render.php", + "helpers/common_helper.php", + "helpers/database_helper.php", + "helpers/date_helper.php", + "helpers/debug_helper.php", + "helpers/download_helper.php", + "helpers/env_helper.php", + "helpers/escape_helper.php", + "helpers/facebook_helper.php", + "helpers/file_helper.php", + "helpers/form_helper.php", + "helpers/gravatar_helper.php", + "helpers/html_helper.php", + "helpers/image_helper.php", + "helpers/ip_helper.php", + "helpers/meta_helper.php", + "helpers/japan_helper.php", + "helpers/money_helper.php", + "helpers/nanoid_helper.php", + "helpers/number_helper.php", + "helpers/paging_helper.php", + "helpers/placeholder_helper.php", + "helpers/request_helper.php", + "helpers/security_helper.php", + "helpers/sentry_helper.php", + "helpers/string_helper.php", + "helpers/text_helper.php", + "helpers/tinyurl_helper.php", + "helpers/url_helper.php", + "helpers/uuid_helper.php", + "helpers/video_embed_helper.php", + "helpers/vn_province_helper.php", + "helpers/xml_helper.php" + ] + }, + "suggest": { + "ext-curl": "Need support CURL", + "ext-json": "Need support JSON", + "nguyenanhung/helpers": "Awesome Helpers - Powerful Library, Helpers and Tools", + "nguyenanhung/image": "Need support for Image Service", + "nguyenanhung/nanoid-helper": "Need support for helper function randomNanoId()", + "nguyenanhung/json-helper": "Need support for JSON", + "nguyenanhung/mobile-helper": "Need support for Mobile Support", + "sentry/sdk": "Need support for Logging with Sentry" + } } diff --git a/helpers/alphaid_helper.php b/helpers/alphaid_helper.php index 456d2b0..165b9ad 100644 --- a/helpers/alphaid_helper.php +++ b/helpers/alphaid_helper.php @@ -8,122 +8,122 @@ * Date: 09/11/2021 * Time: 08:52 */ -if ( ! function_exists('generateAlphaId')) { - /** - * Translates a number to a short alphanumeric version - * - * Translated any number up to 9007199254740992 - * to a shorter version in letters e.g.: - * 9007199254740989 --> PpQXn7COf - * - * specifying the second argument true, it will - * translate back e.g.: - * PpQXn7COf --> 9007199254740989 - * - * this function is based on any2dec && dec2any by - * fragmer[at]mail[dot]ru - * see: http://nl3.php.net/manual/en/function.base-convert.php#52450 - * - * If you want the alphaID to be at least 3 letter long, use the - * $pad_up = 3 argument - * - * In most cases this is better than totally random ID generators - * because this can easily avoid duplicate ID's. - * For example if you correlate the alpha ID to an auto incrementing ID - * in your database, you're done. - * - * The reverse is done because it makes it slightly more cryptic, - * but it also makes it easier to spread lots of IDs in different - * directories on your filesystem. Example: - * $part1 = substr($alpha_id,0,1); - * $part2 = substr($alpha_id,1,1); - * $part3 = substr($alpha_id,2,strlen($alpha_id)); - * $destindir = "/".$part1."/".$part2."/".$part3; - * // by reversing, directories are more evenly spread out. The - * // first 26 directories already occupy 26 main levels - * - * more info on limitation: - * - http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/165372 - * - * if you really need this for bigger numbers you probably have to look - * at things like: http://theserverpages.com/php/manual/en/ref.bc.php - * or: http://theserverpages.com/php/manual/en/ref.gmp.php - * but I haven't really dugg into this. If you have more info on those - * matters feel free to leave a comment. - * - * @param mixed $in String or long input to translate - * @param bool $to_num Reverses translation when true - * @param mixed $pad_up Number or boolean padds the result up to a specified length - * @param mixed $passKey Supplying a password makes it harder to calculate the original ID - * - * @return string string or long - * @author Kevin van Zonneveld - * @author Simon Franz - * @author Deadfish - * @copyright 2008 Kevin van Zonneveld (http://kevin.vanzonneveld.net) - * @license http://www.opensource.org/licenses/bsd-license.php New BSD Licence - * @version SVN: Release: $Id: alphaID.inc.php 344 2009-06-10 17:43:59Z kevin $ - * @link http://kevin.vanzonneveld.net/ - * - */ - function generateAlphaId($in, $to_num = false, $pad_up = false, $passKey = null) - { - $index = "abcdefghijkmnpqrstuvwxyz123456789"; - if ($passKey !== null) { - // Although this function's purpose is to just make the - // ID short - and not so much secure, - // with this patch by Simon Franz (http://blog.snaky.org/) - // you can optionally supply a password to make it harder - // to calculate the corresponding numeric ID - $indexLen = mb_strlen($index); - for ($n = 0; $n < $indexLen; $n++) { - $i[] = $index[$n]; - } - $passHash = hash('sha256', $passKey); - $passHash = (mb_strlen($passHash) < mb_strlen($index)) ? hash('sha512', $passKey) : $passHash; +if (!function_exists('generateAlphaId')) { + /** + * Translates a number to a short alphanumeric version + * + * Translated any number up to 9007199254740992 + * to a shorter version in letters e.g.: + * 9007199254740989 --> PpQXn7COf + * + * specifying the second argument true, it will + * translate back e.g.: + * PpQXn7COf --> 9007199254740989 + * + * this function is based on any2dec && dec2any by + * fragmer[at]mail[dot]ru + * see: http://nl3.php.net/manual/en/function.base-convert.php#52450 + * + * If you want the alphaID to be at least 3 letter long, use the + * $pad_up = 3 argument + * + * In most cases this is better than totally random ID generators + * because this can easily avoid duplicate ID's. + * For example if you correlate the alpha ID to an auto incrementing ID + * in your database, you're done. + * + * The reverse is done because it makes it slightly more cryptic, + * but it also makes it easier to spread lots of IDs in different + * directories on your filesystem. Example: + * $part1 = substr($alpha_id,0,1); + * $part2 = substr($alpha_id,1,1); + * $part3 = substr($alpha_id,2,strlen($alpha_id)); + * $destindir = "/".$part1."/".$part2."/".$part3; + * // by reversing, directories are more evenly spread out. The + * // first 26 directories already occupy 26 main levels + * + * more info on limitation: + * - http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/165372 + * + * if you really need this for bigger numbers you probably have to look + * at things like: http://theserverpages.com/php/manual/en/ref.bc.php + * or: http://theserverpages.com/php/manual/en/ref.gmp.php + * but I haven't really dugg into this. If you have more info on those + * matters feel free to leave a comment. + * + * @param mixed $in String or long input to translate + * @param bool $to_num Reverses translation when true + * @param mixed $pad_up Number or boolean padds the result up to a specified length + * @param mixed $passKey Supplying a password makes it harder to calculate the original ID + * + * @return string string or long + * @author Kevin van Zonneveld + * @author Simon Franz + * @author Deadfish + * @copyright 2008 Kevin van Zonneveld (http://kevin.vanzonneveld.net) + * @license http://www.opensource.org/licenses/bsd-license.php New BSD Licence + * @version SVN: Release: $Id: alphaID.inc.php 344 2009-06-10 17:43:59Z kevin $ + * @link http://kevin.vanzonneveld.net/ + * + */ + function generateAlphaId($in, $to_num = false, $pad_up = false, $passKey = null) + { + $index = "abcdefghijkmnpqrstuvwxyz123456789"; + if ($passKey !== null) { + // Although this function's purpose is to just make the + // ID short - and not so much secure, + // with this patch by Simon Franz (http://blog.snaky.org/) + // you can optionally supply a password to make it harder + // to calculate the corresponding numeric ID + $indexLen = mb_strlen($index); + for ($n = 0; $n < $indexLen; $n++) { + $i[] = $index[$n]; + } + $passHash = hash('sha256', $passKey); + $passHash = (mb_strlen($passHash) < mb_strlen($index)) ? hash('sha512', $passKey) : $passHash; - for ($n = 0; $n < $indexLen; $n++) { - $p[] = $passHash[$n]; - } - array_multisort($p, SORT_DESC, $i); - $index = implode($i); - } - $base = mb_strlen($index); - if ($to_num) { - // Digital number <<-- alphabet letter code - $in = strrev($in); - $out = 0; - $len = mb_strlen($in) - 1; - for ($t = 0; $t <= $len; $t++) { - $pow = $base ** ($len - $t); - $out = $out + mb_strpos($index, $in[$t]) * $pow; - } - if (is_numeric($pad_up)) { - $pad_up--; - if ($pad_up > 0) { - $out -= $base ** $pad_up; - } - } - $out = sprintf('%F', $out); - $out = mb_substr($out, 0, mb_strpos($out, '.')); - } else { - // Digital number -->> alphabet letter code - if (is_numeric($pad_up)) { - $pad_up--; - if ($pad_up > 0) { - $in += $base ** $pad_up; - } - } - $out = ""; - for ($t = floor(log($in, $base)); $t >= 0; $t--) { - $bcp = $base ** $t; - $a = floor($in / $bcp) % $base; - $out .= $index[$a]; - $in -= ($a * $bcp); - } - $out = strrev($out); // reverse - } + for ($n = 0; $n < $indexLen; $n++) { + $p[] = $passHash[$n]; + } + array_multisort($p, SORT_DESC, $i); + $index = implode($i); + } + $base = mb_strlen($index); + if ($to_num) { + // Digital number <<-- alphabet letter code + $in = strrev($in); + $out = 0; + $len = mb_strlen($in) - 1; + for ($t = 0; $t <= $len; $t++) { + $pow = $base ** ($len - $t); + $out = $out + mb_strpos($index, $in[$t]) * $pow; + } + if (is_numeric($pad_up)) { + $pad_up--; + if ($pad_up > 0) { + $out -= $base ** $pad_up; + } + } + $out = sprintf('%F', $out); + $out = mb_substr($out, 0, mb_strpos($out, '.')); + } else { + // Digital number -->> alphabet letter code + if (is_numeric($pad_up)) { + $pad_up--; + if ($pad_up > 0) { + $in += $base ** $pad_up; + } + } + $out = ""; + for ($t = floor(log($in, $base)); $t >= 0; $t--) { + $bcp = $base ** $t; + $a = floor($in / $bcp) % $base; + $out .= $index[$a]; + $in -= ($a * $bcp); + } + $out = strrev($out); // reverse + } - return $out; - } + return $out; + } } diff --git a/helpers/array_helper.php b/helpers/array_helper.php index 472b276..27af33d 100644 --- a/helpers/array_helper.php +++ b/helpers/array_helper.php @@ -8,472 +8,472 @@ * Date: 08/07/2021 * Time: 01:12 */ -if ( ! function_exists('arrayToObject')) { - /** - * Function arrayToObject - * - * @param array|mixed $array - * - * @return array|false|\stdClass - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 07/27/2021 36:10 - */ - function arrayToObject($array = array()) - { - if ( ! is_array($array)) { - return $array; - } - $object = new stdClass(); - $countArray = count($array); - if ($countArray > 0) { - foreach ($array as $name => $value) { - if ( ! empty($name)) { - $object->$name = arrayToObject($value); - } - } - return $object; - } - return false; - } +if (!function_exists('arrayToObject')) { + /** + * Function arrayToObject + * + * @param array|mixed $array + * + * @return array|false|\stdClass + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 07/27/2021 36:10 + */ + function arrayToObject($array = array()) + { + if (!is_array($array)) { + return $array; + } + $object = new stdClass(); + $countArray = count($array); + if ($countArray > 0) { + foreach ($array as $name => $value) { + if (!empty($name)) { + $object->$name = arrayToObject($value); + } + } + return $object; + } + return false; + } } -if ( ! function_exists('arrayToXml')) { - /** - * Function arrayToXml - * - * @param array|mixed $array - * @param string $namespace - * @param mixed $file_output - * - * @return bool|string|null - * @throws \Exception - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/20/2021 13:21 - */ - function arrayToXml($array = array(), $namespace = '', $file_output = null) - { - if (class_exists('SimpleXMLElement')) { - $xml_object = new SimpleXMLElement( - "<" . $namespace . ">" - ); // creating object of SimpleXMLElement - convertArrayToXml($array, $xml_object); // function call to convert array to xml - $xml_file = $file_output !== null ? $xml_object->asXML($file_output) : $xml_object->asXML( - ); // saving generated xml file - return ! empty($xml_file) ? $xml_file : null; - } - return null; - } +if (!function_exists('arrayToXml')) { + /** + * Function arrayToXml + * + * @param array|mixed $array + * @param string $namespace + * @param mixed $file_output + * + * @return bool|string|null + * @throws \Exception + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/20/2021 13:21 + */ + function arrayToXml($array = array(), $namespace = '', $file_output = null) + { + if (class_exists('SimpleXMLElement')) { + $xml_object = new SimpleXMLElement( + "<" . $namespace . ">" + ); // creating object of SimpleXMLElement + convertArrayToXml($array, $xml_object); // function call to convert array to xml + $xml_file = $file_output !== null ? $xml_object->asXML($file_output) : $xml_object->asXML( + ); // saving generated xml file + return !empty($xml_file) ? $xml_file : null; + } + return null; + } } -if ( ! function_exists('convertArrayToXml')) { - /** - * Function convertArrayToXml - * - * @param $array - * @param $SimpleXMLElement - * - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/07/2021 19:35 - */ - function convertArrayToXml($array, &$SimpleXMLElement) - { - foreach ($array as $key => $value) { - if (is_array($value)) { - if ( ! is_numeric($key)) { - $subNode = $SimpleXMLElement->addChild((string)$key); - } else { - $subNode = $SimpleXMLElement->addChild("item" . $key); - } - convertArrayToXml($value, $subNode); - } else { - $SimpleXMLElement->addChild((string)$key, htmlspecialchars((string)$value)); - } - } - } +if (!function_exists('convertArrayToXml')) { + /** + * Function convertArrayToXml + * + * @param $array + * @param $SimpleXMLElement + * + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/07/2021 19:35 + */ + function convertArrayToXml($array, &$SimpleXMLElement) + { + foreach ($array as $key => $value) { + if (is_array($value)) { + if (!is_numeric($key)) { + $subNode = $SimpleXMLElement->addChild((string)$key); + } else { + $subNode = $SimpleXMLElement->addChild("item" . $key); + } + convertArrayToXml($value, $subNode); + } else { + $SimpleXMLElement->addChild((string)$key, htmlspecialchars((string)$value)); + } + } + } } -if ( ! function_exists('removeArrayElementWithValue')) { - /** - * Function removeArrayElementWithValue - Loại bỏ 1 giá trị trong array theo key và value - * - * @param $array - * @param $key - * @param $value - * - * @return mixed - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 12/12/2022 37:59 - */ - function removeArrayElementWithValue($array, $key, $value) - { - foreach ($array as $subKey => $subArray) { - if (isset($subArray[$key]) && $subArray[$key] === $value) { - unset($array[$subKey]); - } - } - return $array; - } +if (!function_exists('removeArrayElementWithValue')) { + /** + * Function removeArrayElementWithValue - Loại bỏ 1 giá trị trong array theo key và value + * + * @param $array + * @param $key + * @param $value + * + * @return mixed + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 12/12/2022 37:59 + */ + function removeArrayElementWithValue($array, $key, $value) + { + foreach ($array as $subKey => $subArray) { + if (isset($subArray[$key]) && $subArray[$key] === $value) { + unset($array[$subKey]); + } + } + return $array; + } } -if ( ! function_exists('arrayRecursiveDiff')) { - /** - * Function arrayRecursiveDiff - Diff 2 array bằng đệ quy - * - * @param $aArray1 - * @param $aArray2 - * - * @return array - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 12/12/2022 39:34 - */ - function arrayRecursiveDiff($aArray1, $aArray2) - { - $aReturn = array(); - foreach ($aArray1 as $mKey => $mValue) { - if (array_key_exists($mKey, $aArray2)) { - if (is_array($mValue)) { - $aRecursiveDiff = arrayRecursiveDiff($mValue, $aArray2[$mKey]); - if (count($aRecursiveDiff)) { - $aReturn[$mKey] = $aRecursiveDiff; - } - } elseif ($mValue !== $aArray2[$mKey]) { - $aReturn[$mKey] = $mValue; - } - } else { - $aReturn[$mKey] = $mValue; - } - } - return $aReturn; - } +if (!function_exists('arrayRecursiveDiff')) { + /** + * Function arrayRecursiveDiff - Diff 2 array bằng đệ quy + * + * @param $aArray1 + * @param $aArray2 + * + * @return array + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 12/12/2022 39:34 + */ + function arrayRecursiveDiff($aArray1, $aArray2) + { + $aReturn = array(); + foreach ($aArray1 as $mKey => $mValue) { + if (array_key_exists($mKey, $aArray2)) { + if (is_array($mValue)) { + $aRecursiveDiff = arrayRecursiveDiff($mValue, $aArray2[$mKey]); + if (count($aRecursiveDiff)) { + $aReturn[$mKey] = $aRecursiveDiff; + } + } elseif ($mValue !== $aArray2[$mKey]) { + $aReturn[$mKey] = $mValue; + } + } else { + $aReturn[$mKey] = $mValue; + } + } + return $aReturn; + } } -if ( ! function_exists('arrayIsAssoc')) { - /** - * Function arrayIsAssoc - Detects if the given value is an associative array. - * - * ### arrayIsAssoc - * Related global function (description see above). - * - * > #### [( jump back )](#available-php-functions) - * - * ```php - * arrayIsAssoc( array $array ): boolean - * ``` - * - * #### Example - * ```php - * $array = [ - * 'foo' => 'bar' - * ]; - * - * arrayIsAssoc( $array ); - * - * // bool(true) - * ``` - * - * @param array $array - * Any type of array. - * - * @return bool - * True if the array is associative, false otherwise. - */ - function arrayIsAssoc($array) - { - if ( ! is_array($array) || $array === array()) { - return false; - } - return array_keys($array) !== range(0, count($array) - 1); - } +if (!function_exists('arrayIsAssoc')) { + /** + * Function arrayIsAssoc - Detects if the given value is an associative array. + * + * ### arrayIsAssoc + * Related global function (description see above). + * + * > #### [( jump back )](#available-php-functions) + * + * ```php + * arrayIsAssoc( array $array ): boolean + * ``` + * + * #### Example + * ```php + * $array = [ + * 'foo' => 'bar' + * ]; + * + * arrayIsAssoc( $array ); + * + * // bool(true) + * ``` + * + * @param array $array + * Any type of array. + * + * @return bool + * True if the array is associative, false otherwise. + */ + function arrayIsAssoc($array) + { + if (!is_array($array) || $array === array()) { + return false; + } + return array_keys($array) !== range(0, count($array) - 1); + } } -if ( ! function_exists('arrayFirstElement')) { - /** - * Function arrayFirstElement - Returns the first element of an array. - * - * ### arrayFirstElement - * Related global function (description see above). - * - * > #### [( jump back )](#available-php-functions) - * - * ```php - * arrayFirstElement( array $array ): mixed - * ``` - * - * #### Example - * ```php - * $array = [ - * 'foo' => 'bar', - * 'baz' => 'qux' - * ]; - * - * arrayFirstElement( $array ) - * - * // bar - * ``` - * - * @param array $array - * The concerned array. - * - * @return mixed - * The value of the first element, without key. Mixed type. - * - */ - function arrayFirstElement($array) - { - return $array[array_keys($array)[0]]; - } +if (!function_exists('arrayFirstElement')) { + /** + * Function arrayFirstElement - Returns the first element of an array. + * + * ### arrayFirstElement + * Related global function (description see above). + * + * > #### [( jump back )](#available-php-functions) + * + * ```php + * arrayFirstElement( array $array ): mixed + * ``` + * + * #### Example + * ```php + * $array = [ + * 'foo' => 'bar', + * 'baz' => 'qux' + * ]; + * + * arrayFirstElement( $array ) + * + * // bar + * ``` + * + * @param array $array + * The concerned array. + * + * @return mixed + * The value of the first element, without key. Mixed type. + * + */ + function arrayFirstElement($array) + { + return $array[array_keys($array)[0]]; + } } -if ( ! function_exists('arrayLastElement')) { - /** - * Function arrayLastElement - Returns the last element of an array. - * - * ### arrayLastElement - * Related global function (description see above). - * - * > #### [( jump back )](#available-php-functions) - * - * ```php - * arrayLastElement( array $array ): mixed - * ``` - * - * #### Example - * ```php - * $array = [ - * 'foo' => 'bar', - * 'baz' => 'qux' - * ]; - * - * arrayLastElement( $array ) - * - * // qux - * ``` - * - * @param array $array - * The concerned array. - * - * @return mixed - * The value of the last element, without key. Mixed type. - */ - function arrayLastElement($array) - { - return $array[array_keys($array)[count($array) - 1]]; - } +if (!function_exists('arrayLastElement')) { + /** + * Function arrayLastElement - Returns the last element of an array. + * + * ### arrayLastElement + * Related global function (description see above). + * + * > #### [( jump back )](#available-php-functions) + * + * ```php + * arrayLastElement( array $array ): mixed + * ``` + * + * #### Example + * ```php + * $array = [ + * 'foo' => 'bar', + * 'baz' => 'qux' + * ]; + * + * arrayLastElement( $array ) + * + * // qux + * ``` + * + * @param array $array + * The concerned array. + * + * @return mixed + * The value of the last element, without key. Mixed type. + */ + function arrayLastElement($array) + { + return $array[array_keys($array)[count($array) - 1]]; + } } -if ( ! function_exists('arrayGetElement')) { - /** - * Function arrayGetElement - Gets a value in an array by dot notation for the keys. - * - * ### arrayGetElement - * Related global function (description see above). - * - * > #### [( jump back )](#available-php-functions) - * - * ```php - * arrayGetElement( string key, array $array ): mixed - * ``` - * - * #### Example - * ```php - * $array = [ - * 'foo' => 'bar', - * 'baz' => [ - * 'qux => 'foobar' - * ] - * ]; - * - * arrayGetElement( 'baz.qux', $array ); - * - * // foobar - * ``` - * - * @param string $key - * The key by dot notation. - * @param array $array - * The array to search in. - * - * @return mixed - * The searched value, null otherwise. - */ - function arrayGetElement($key, $array) - { - if (is_string($key) && is_array($array)) { - $keys = explode('.', $key); - while (count($keys) >= 1) { - $k = array_shift($keys); - if ( ! isset($array[$k])) { - return null; - } - if (count($keys) === 0) { - return $array[$k]; - } - $array = &$array[$k]; - } - } - return null; - } +if (!function_exists('arrayGetElement')) { + /** + * Function arrayGetElement - Gets a value in an array by dot notation for the keys. + * + * ### arrayGetElement + * Related global function (description see above). + * + * > #### [( jump back )](#available-php-functions) + * + * ```php + * arrayGetElement( string key, array $array ): mixed + * ``` + * + * #### Example + * ```php + * $array = [ + * 'foo' => 'bar', + * 'baz' => [ + * 'qux => 'foobar' + * ] + * ]; + * + * arrayGetElement( 'baz.qux', $array ); + * + * // foobar + * ``` + * + * @param string $key + * The key by dot notation. + * @param array $array + * The array to search in. + * + * @return mixed + * The searched value, null otherwise. + */ + function arrayGetElement($key, $array) + { + if (is_string($key) && is_array($array)) { + $keys = explode('.', $key); + while (count($keys) >= 1) { + $k = array_shift($keys); + if (!isset($array[$k])) { + return null; + } + if (count($keys) === 0) { + return $array[$k]; + } + $array = &$array[$k]; + } + } + return null; + } } -if ( ! function_exists('arraySetElement')) { - /** - * Function arraySetElement - Sets a value in an array using the dot notation. - * - * ### arraySetElement - * Related global function (description see above). - * - * > #### [( jump back )](#available-php-functions) - * - * ```php - * arraySetElement( string key, mixed value, array $array ): boolean - * ``` - * - * #### Example 1 - * ```php - * $array = [ - * 'foo' => 'bar', - * 'baz' => [ - * 'qux => 'foobar' - * ] - * ]; - * - * arraySetElement( 'baz.qux', 'bazqux', $array ); - * - * // ( - * // [foo] => bar - * // [baz] => [ - * // [qux] => bazqux - * // ] - * // ) - * ``` - * - * #### Example 2 - * ```php - * $array = [ - * 'foo' => 'bar', - * 'baz' => [ - * 'qux => 'foobar' - * ] - * ]; - * - * arraySetElement( 'baz.foo', 'bar', $array ); - * - * // ( - * // [foo] => bar - * // [baz] => [ - * // [qux] => bazqux - * // [foo] => bar - * // ] - * // ) - * ``` - * - * @param string $key - * The key to set using dot notation. - * @param mixed $value - * The value to set on the specified key. - * @param array $array - * The concerned array. - * - * @return bool - * True if the new value was successfully set, false otherwise. - */ - function arraySetElement($key, $value, &$array) - { - if (is_string($key) && ! empty($key)) { - $keys = explode('.', $key); - $arrTmp = &$array; - while (count($keys) >= 1) { - $k = array_shift($keys); - if ( ! is_array($arrTmp)) { - $arrTmp = array(); - } - if ( ! isset($arrTmp[$k])) { - $arrTmp[$k] = array(); - } - if (count($keys) === 0) { - $arrTmp[$k] = $value; - return true; - } - $arrTmp = &$arrTmp[$k]; - } - } - return false; - } +if (!function_exists('arraySetElement')) { + /** + * Function arraySetElement - Sets a value in an array using the dot notation. + * + * ### arraySetElement + * Related global function (description see above). + * + * > #### [( jump back )](#available-php-functions) + * + * ```php + * arraySetElement( string key, mixed value, array $array ): boolean + * ``` + * + * #### Example 1 + * ```php + * $array = [ + * 'foo' => 'bar', + * 'baz' => [ + * 'qux => 'foobar' + * ] + * ]; + * + * arraySetElement( 'baz.qux', 'bazqux', $array ); + * + * // ( + * // [foo] => bar + * // [baz] => [ + * // [qux] => bazqux + * // ] + * // ) + * ``` + * + * #### Example 2 + * ```php + * $array = [ + * 'foo' => 'bar', + * 'baz' => [ + * 'qux => 'foobar' + * ] + * ]; + * + * arraySetElement( 'baz.foo', 'bar', $array ); + * + * // ( + * // [foo] => bar + * // [baz] => [ + * // [qux] => bazqux + * // [foo] => bar + * // ] + * // ) + * ``` + * + * @param string $key + * The key to set using dot notation. + * @param mixed $value + * The value to set on the specified key. + * @param array $array + * The concerned array. + * + * @return bool + * True if the new value was successfully set, false otherwise. + */ + function arraySetElement($key, $value, &$array) + { + if (is_string($key) && !empty($key)) { + $keys = explode('.', $key); + $arrTmp = &$array; + while (count($keys) >= 1) { + $k = array_shift($keys); + if (!is_array($arrTmp)) { + $arrTmp = array(); + } + if (!isset($arrTmp[$k])) { + $arrTmp[$k] = array(); + } + if (count($keys) === 0) { + $arrTmp[$k] = $value; + return true; + } + $arrTmp = &$arrTmp[$k]; + } + } + return false; + } } -if ( ! function_exists('to_array')) { - /** - * Function to_array - Converts a string or an object to an array. - * - * ### to_array - * Related global function (description see above). - * - * > #### [( jump back )](#available-php-functions) - * - * ```php - * to_array( string|object $var ): array|null - * ``` - * - * #### Example 1 (string) - * ```php - * $var = 'php'; - * to_array( $var ); - * - * // ( - * // [0] => p - * // [1] => h - * // [2] => p - * // ) - * - * ``` - * #### Example 2 (object) - * ```php - * $var = new stdClass; - * $var->foo = 'bar'; - * - * to_array( $var ); - * - * // ( - * // [foo] => bar - * // ) - * ``` - * - * @param string|object $var - * String or object. - * - * @return array|null - * An array representation of the converted string or object. - * Returns null on error. - */ - function to_array($var) - { - if (is_string($var)) { - return str_split($var); - } - if (is_object($var)) { - return json_decode(json_encode($var), true); - } - return null; - } +if (!function_exists('to_array')) { + /** + * Function to_array - Converts a string or an object to an array. + * + * ### to_array + * Related global function (description see above). + * + * > #### [( jump back )](#available-php-functions) + * + * ```php + * to_array( string|object $var ): array|null + * ``` + * + * #### Example 1 (string) + * ```php + * $var = 'php'; + * to_array( $var ); + * + * // ( + * // [0] => p + * // [1] => h + * // [2] => p + * // ) + * + * ``` + * #### Example 2 (object) + * ```php + * $var = new stdClass; + * $var->foo = 'bar'; + * + * to_array( $var ); + * + * // ( + * // [foo] => bar + * // ) + * ``` + * + * @param string|object $var + * String or object. + * + * @return array|null + * An array representation of the converted string or object. + * Returns null on error. + */ + function to_array($var) + { + if (is_string($var)) { + return str_split($var); + } + if (is_object($var)) { + return json_decode(json_encode($var), true); + } + return null; + } } -if ( ! function_exists('arrayToAttributes')) { - /** - * Takes an array of attributes and turns it into a string for an html tag - * - * @param array $attr - * - * @return string - */ - function arrayToAttributes($attr) - { - $attr_str = ''; - foreach ((array)$attr as $property => $value) { - // Ignore null/false - if ($value === null || $value === false) { - continue; - } - // If the key is numeric then it must be something like selected="selected" - if (is_numeric($property)) { - $property = $value; - } - $attr_str .= $property . '="' . str_replace('"', '"', $value) . '" '; - } - // We strip off the last space for return - return trim($attr_str); - } +if (!function_exists('arrayToAttributes')) { + /** + * Takes an array of attributes and turns it into a string for an html tag + * + * @param array $attr + * + * @return string + */ + function arrayToAttributes($attr) + { + $attr_str = ''; + foreach ((array)$attr as $property => $value) { + // Ignore null/false + if ($value === null || $value === false) { + continue; + } + // If the key is numeric then it must be something like selected="selected" + if (is_numeric($property)) { + $property = $value; + } + $attr_str .= $property . '="' . str_replace('"', '"', $value) . '" '; + } + // We strip off the last space for return + return trim($attr_str); + } } diff --git a/helpers/assets_helper.php b/helpers/assets_helper.php index ea79ecb..45c6dea 100644 --- a/helpers/assets_helper.php +++ b/helpers/assets_helper.php @@ -8,399 +8,399 @@ * Date: 08/07/2021 * Time: 01:11 */ -if ( ! function_exists('assets_url')) { - /** - * Function assets_url - * - * @param string $uri - * @param string|null $protocol - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/07/2021 11:56 - */ - function assets_url($uri = '', $protocol = null) - { - if (function_exists('base_url') && function_exists('config_item')) { - $fileExt = mb_substr(trim($uri), mb_strrpos(trim($uri), '.') + 1); - $fileExt = mb_strtoupper($fileExt); - $version = ''; - if ($fileExt === 'CSS' || $fileExt === 'JS') { - $version = config_item('assets_version'); - } - return trim(base_url('assets/' . $uri, $protocol) . $version); - } - return trim($uri); - } +if (!function_exists('assets_url')) { + /** + * Function assets_url + * + * @param string $uri + * @param string|null $protocol + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/07/2021 11:56 + */ + function assets_url($uri = '', $protocol = null) + { + if (function_exists('base_url') && function_exists('config_item')) { + $fileExt = mb_substr(trim($uri), mb_strrpos(trim($uri), '.') + 1); + $fileExt = mb_strtoupper($fileExt); + $version = ''; + if ($fileExt === 'CSS' || $fileExt === 'JS') { + $version = config_item('assets_version'); + } + return trim(base_url('assets/' . $uri, $protocol) . $version); + } + return trim($uri); + } } -if ( ! function_exists('static_url')) { - /** - * Function static_url - * - * @param string $uri - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/07/2021 11:56 - */ - function static_url($uri = '') - { - if (function_exists('base_url') && function_exists('config_item')) { - $fileExt = mb_substr(trim($uri), mb_strrpos(trim($uri), '.') + 1); - $fileExt = mb_strtoupper($fileExt); - $version = ''; - if ($fileExt === 'CSS' || $fileExt === 'JS') { - $version = config_item('assets_version'); - } - $host = config_item('static_url'); - return trim($host) . trim($uri) . trim($version); - } - return trim($uri); - } +if (!function_exists('static_url')) { + /** + * Function static_url + * + * @param string $uri + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/07/2021 11:56 + */ + function static_url($uri = '') + { + if (function_exists('base_url') && function_exists('config_item')) { + $fileExt = mb_substr(trim($uri), mb_strrpos(trim($uri), '.') + 1); + $fileExt = mb_strtoupper($fileExt); + $version = ''; + if ($fileExt === 'CSS' || $fileExt === 'JS') { + $version = config_item('assets_version'); + } + $host = config_item('static_url'); + return trim($host) . trim($uri) . trim($version); + } + return trim($uri); + } } -if ( ! function_exists('templates_url')) { - /** - * Function templates_url - * - * @param string $uri - * @param string|null $protocol - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/07/2021 12:12 - */ - function templates_url($uri = '', $protocol = null) - { - if (function_exists('base_url') && function_exists('config_item')) { - $fileExt = mb_substr(trim($uri), mb_strrpos(trim($uri), '.') + 1); - $fileExt = mb_strtoupper($fileExt); - $version = ''; - if ($fileExt === 'CSS' || $fileExt === 'JS') { - $version = config_item('assets_version'); - } - return trim(base_url('templates/' . $uri, $protocol) . $version); - } - return trim($uri); - } +if (!function_exists('templates_url')) { + /** + * Function templates_url + * + * @param string $uri + * @param string|null $protocol + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/07/2021 12:12 + */ + function templates_url($uri = '', $protocol = null) + { + if (function_exists('base_url') && function_exists('config_item')) { + $fileExt = mb_substr(trim($uri), mb_strrpos(trim($uri), '.') + 1); + $fileExt = mb_strtoupper($fileExt); + $version = ''; + if ($fileExt === 'CSS' || $fileExt === 'JS') { + $version = config_item('assets_version'); + } + return trim(base_url('templates/' . $uri, $protocol) . $version); + } + return trim($uri); + } } -if ( ! function_exists('editor_url')) { - /** - * Function editor_url - * - * @param string $uri - * @param string|null $protocol - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 12/09/2020 47:57 - */ - function editor_url($uri = '', $protocol = null) - { - $uri = 'editors/' . $uri; - return assets_url($uri, $protocol); - } +if (!function_exists('editor_url')) { + /** + * Function editor_url + * + * @param string $uri + * @param string|null $protocol + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 12/09/2020 47:57 + */ + function editor_url($uri = '', $protocol = null) + { + $uri = 'editors/' . $uri; + return assets_url($uri, $protocol); + } } -if ( ! function_exists('favicon_url')) { - /** - * Function favicon_url - * - * @param string $uri - * @param string|null $protocol - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 12/09/2020 47:51 - */ - function favicon_url($uri = '', $protocol = null) - { - $uri = 'favicon/' . $uri; - return assets_url($uri, $protocol); - } +if (!function_exists('favicon_url')) { + /** + * Function favicon_url + * + * @param string $uri + * @param string|null $protocol + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 12/09/2020 47:51 + */ + function favicon_url($uri = '', $protocol = null) + { + $uri = 'favicon/' . $uri; + return assets_url($uri, $protocol); + } } -if ( ! function_exists('fav_url')) { - /** - * Function fav_url - alias of favicon_url - * - * @param string $uri - * @param string|null $protocol - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 12/09/2020 47:51 - */ - function fav_url($uri = '', $protocol = null) - { - $uri = 'fav/' . $uri; - return assets_url($uri, $protocol); - } +if (!function_exists('fav_url')) { + /** + * Function fav_url - alias of favicon_url + * + * @param string $uri + * @param string|null $protocol + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 12/09/2020 47:51 + */ + function fav_url($uri = '', $protocol = null) + { + $uri = 'fav/' . $uri; + return assets_url($uri, $protocol); + } } -if ( ! function_exists('favicon_html_tag')) { - /** - * Function favicon_html_tag - * - * @param $baseUrl - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 30/12/2022 03:21 - */ - function favicon_html_tag($baseUrl = '') - { - return (new \nguyenanhung\CodeIgniter\BasicHelper\Favicon())->faviconHtml($baseUrl); - } +if (!function_exists('favicon_html_tag')) { + /** + * Function favicon_html_tag + * + * @param $baseUrl + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 30/12/2022 03:21 + */ + function favicon_html_tag($baseUrl = '') + { + return (new \nguyenanhung\CodeIgniter\BasicHelper\Favicon())->faviconHtml($baseUrl); + } } -if ( ! function_exists('storage_url')) { - /** - * Function storage_url - * - * @param string $uri - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/07/2021 48:52 - */ - function storage_url($uri = '') - { - if (function_exists('config_item')) { - $fileExt = mb_substr(trim($uri), mb_strrpos(trim($uri), '.') + 1); - $fileExt = mb_strtoupper($fileExt); - $version = ''; - if ($fileExt === 'CSS' || $fileExt === 'JS') { - $version = config_item('assets_version'); - } - $storageUrl = trim(config_item('storage_url')) . trim($uri) . $version; - return trim($storageUrl); - } - return $uri; - } +if (!function_exists('storage_url')) { + /** + * Function storage_url + * + * @param string $uri + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/07/2021 48:52 + */ + function storage_url($uri = '') + { + if (function_exists('config_item')) { + $fileExt = mb_substr(trim($uri), mb_strrpos(trim($uri), '.') + 1); + $fileExt = mb_strtoupper($fileExt); + $version = ''; + if ($fileExt === 'CSS' || $fileExt === 'JS') { + $version = config_item('assets_version'); + } + $storageUrl = trim(config_item('storage_url')) . trim($uri) . $version; + return trim($storageUrl); + } + return $uri; + } } -if ( ! function_exists('public_storage_tmp_url')) { - /** - * Function public_storage_tmp_url - * - * @param string $uri - * @param string|null $protocol - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 21/07/2022 41:10 - */ - function public_storage_tmp_url($uri = '', $protocol = null) - { - if (function_exists('base_url') && function_exists('config_item')) { - $fileExt = mb_substr(trim($uri), mb_strrpos(trim($uri), '.') + 1); - $fileExt = mb_strtoupper($fileExt); - $version = ''; - if ($fileExt === 'CSS' || $fileExt === 'JS') { - $version = config_item('assets_version'); - } - return trim(base_url('storage/tmp/' . $uri, $protocol) . $version); - } - return trim($uri); - } +if (!function_exists('public_storage_tmp_url')) { + /** + * Function public_storage_tmp_url + * + * @param string $uri + * @param string|null $protocol + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 21/07/2022 41:10 + */ + function public_storage_tmp_url($uri = '', $protocol = null) + { + if (function_exists('base_url') && function_exists('config_item')) { + $fileExt = mb_substr(trim($uri), mb_strrpos(trim($uri), '.') + 1); + $fileExt = mb_strtoupper($fileExt); + $version = ''; + if ($fileExt === 'CSS' || $fileExt === 'JS') { + $version = config_item('assets_version'); + } + return trim(base_url('storage/tmp/' . $uri, $protocol) . $version); + } + return trim($uri); + } } -if ( ! function_exists('go_url')) { - /** - * Function go_url - * - * @param string $uri - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/16/2021 41:37 - */ - function go_url($uri = '') - { - if (function_exists('config_item')) { - $goUrl = trim(config_item('go_url')) . trim($uri); - return trim($goUrl); - } - return $uri; - } +if (!function_exists('go_url')) { + /** + * Function go_url + * + * @param string $uri + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/16/2021 41:37 + */ + function go_url($uri = '') + { + if (function_exists('config_item')) { + $goUrl = trim(config_item('go_url')) . trim($uri); + return trim($goUrl); + } + return $uri; + } } -if ( ! function_exists('assets_mobile')) { - /** - * Function assets_mobile - * - * @param string $uri - * @param string|null $protocol - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 12/09/2020 47:34 - */ - function assets_mobile($uri = '', $protocol = null) - { - $uri = 'mobile/assets/' . $uri; - return assets_url($uri, $protocol); - } +if (!function_exists('assets_mobile')) { + /** + * Function assets_mobile + * + * @param string $uri + * @param string|null $protocol + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 12/09/2020 47:34 + */ + function assets_mobile($uri = '', $protocol = null) + { + $uri = 'mobile/assets/' . $uri; + return assets_url($uri, $protocol); + } } -if ( ! function_exists('assets_themes')) { - /** - * Function assets_themes - * - * @param string $themes - * @param string $uri - * @param string $folder - * @param string|null $protocol - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 12/09/2020 47:39 - */ - function assets_themes($themes = '', $uri = '', $folder = 'yes', $protocol = null) - { - // Hooks format - $themes = str_replace('itravels', 'iTravels', $themes); - // Pattern - if ($themes !== '') { - if ($folder !== 'no') { - $uri = 'themes/' . $themes . '/assets/' . $uri; - } else { - $uri = 'themes/' . $themes . '/' . $uri; - } - } elseif ($folder === 'no') { - $uri = 'themes/' . $uri; - } else { - $uri = 'themes/assets/' . $uri; - } - return assets_url($uri, $protocol); - } +if (!function_exists('assets_themes')) { + /** + * Function assets_themes + * + * @param string $themes + * @param string $uri + * @param string $folder + * @param string|null $protocol + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 12/09/2020 47:39 + */ + function assets_themes($themes = '', $uri = '', $folder = 'yes', $protocol = null) + { + // Hooks format + $themes = str_replace('itravels', 'iTravels', $themes); + // Pattern + if ($themes !== '') { + if ($folder !== 'no') { + $uri = 'themes/' . $themes . '/assets/' . $uri; + } else { + $uri = 'themes/' . $themes . '/' . $uri; + } + } elseif ($folder === 'no') { + $uri = 'themes/' . $uri; + } else { + $uri = 'themes/assets/' . $uri; + } + return assets_url($uri, $protocol); + } } -if ( ! function_exists('assets_themes_dashboard')) { - /** - * Function assets_themes_dashboard - * - * @param string $themes - * @param string $uri - * @param string $folder - * @param string|null $protocol - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 12/09/2020 48:37 - */ - function assets_themes_dashboard($themes = '', $uri = '', $folder = 'yes', $protocol = null) - { - return assets_themes($themes, $uri, $folder, $protocol); - } +if (!function_exists('assets_themes_dashboard')) { + /** + * Function assets_themes_dashboard + * + * @param string $themes + * @param string $uri + * @param string $folder + * @param string|null $protocol + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 12/09/2020 48:37 + */ + function assets_themes_dashboard($themes = '', $uri = '', $folder = 'yes', $protocol = null) + { + return assets_themes($themes, $uri, $folder, $protocol); + } } -if ( ! function_exists('assets_themes_comingsoon')) { - /** - * Function assets_themes_comingsoon - * - * @param string $themes - * @param string $uri - * @param string $folder - * @param string|null $protocol - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 12/09/2020 48:22 - */ - function assets_themes_comingsoon($themes = '', $uri = '', $folder = '', $protocol = null) - { - return assets_themes($themes, $uri, $folder, $protocol); - } +if (!function_exists('assets_themes_comingsoon')) { + /** + * Function assets_themes_comingsoon + * + * @param string $themes + * @param string $uri + * @param string $folder + * @param string|null $protocol + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 12/09/2020 48:22 + */ + function assets_themes_comingsoon($themes = '', $uri = '', $folder = '', $protocol = null) + { + return assets_themes($themes, $uri, $folder, $protocol); + } } -if ( ! function_exists('assets_themes_error')) { - /** - * Function assets_themes_error - * - * @param string $themes - * @param string $uri - * @param string $folder - * @param string|null $protocol - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 12/09/2020 48:14 - */ - function assets_themes_error($themes = '', $uri = '', $folder = 'yes', $protocol = null) - { - return assets_themes($themes, $uri, $folder, $protocol); - } +if (!function_exists('assets_themes_error')) { + /** + * Function assets_themes_error + * + * @param string $themes + * @param string $uri + * @param string $folder + * @param string|null $protocol + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 12/09/2020 48:14 + */ + function assets_themes_error($themes = '', $uri = '', $folder = 'yes', $protocol = null) + { + return assets_themes($themes, $uri, $folder, $protocol); + } } -if ( ! function_exists('assets_themes_metronic')) { - /** - * Function assets_themes_metronic - * - * @param string $uri - * @param string|null $protocol - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 10/05/2021 23:38 - */ - function assets_themes_metronic($uri = '', $protocol = null) - { - return assets_themes('metronic', $uri, 'yes', $protocol); - } +if (!function_exists('assets_themes_metronic')) { + /** + * Function assets_themes_metronic + * + * @param string $uri + * @param string|null $protocol + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 10/05/2021 23:38 + */ + function assets_themes_metronic($uri = '', $protocol = null) + { + return assets_themes('metronic', $uri, 'yes', $protocol); + } } -if ( ! function_exists('cdn_js_url')) { - /** - * Function cdn_js_url - * - * @param string $uri - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 09/11/2021 18:15 - */ - function cdn_js_url($uri = '') - { - $cdnJs = '//cdnjs.cloudflare.com/ajax/libs/'; - return $cdnJs . trim($uri); - } +if (!function_exists('cdn_js_url')) { + /** + * Function cdn_js_url + * + * @param string $uri + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 09/11/2021 18:15 + */ + function cdn_js_url($uri = '') + { + $cdnJs = '//cdnjs.cloudflare.com/ajax/libs/'; + return $cdnJs . trim($uri); + } } -if ( ! function_exists('google_fonts_url')) { - /** - * Function google_fonts_url - * - * @param string $family - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 09/11/2021 19:14 - */ - function google_fonts_url($family = '') - { - $fonts = '//fonts.googleapis.com/css?family='; - return $fonts . trim($family); - } +if (!function_exists('google_fonts_url')) { + /** + * Function google_fonts_url + * + * @param string $family + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 09/11/2021 19:14 + */ + function google_fonts_url($family = '') + { + $fonts = '//fonts.googleapis.com/css?family='; + return $fonts . trim($family); + } } -if ( ! function_exists('bootstrapcdn_url')) { - /** - * Function bootstrapcdn_url - * - * @param string $uri - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 09/11/2021 22:45 - */ - function bootstrapcdn_url($uri = '') - { - $cdn = '//maxcdn.bootstrapcdn.com/bootstrap/'; - return $cdn . trim($uri); - } +if (!function_exists('bootstrapcdn_url')) { + /** + * Function bootstrapcdn_url + * + * @param string $uri + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 09/11/2021 22:45 + */ + function bootstrapcdn_url($uri = '') + { + $cdn = '//maxcdn.bootstrapcdn.com/bootstrap/'; + return $cdn . trim($uri); + } } diff --git a/helpers/blogspot_helper.php b/helpers/blogspot_helper.php index 586354b..ac9dd95 100644 --- a/helpers/blogspot_helper.php +++ b/helpers/blogspot_helper.php @@ -8,53 +8,53 @@ * Date: 09/01/2023 * Time: 00:26 */ -if ( ! function_exists('blogspotDescSortWithPublishedTime')) { - function blogspotDescSortWithPublishedTime($item1, $item2) - { - if ($item1['published']['$t'] === $item2['published']['$t']) { - return 0; - } - return ($item1['published']['$t'] < $item2['published']['$t']) ? 1 : -1; - } +if (!function_exists('blogspotDescSortWithPublishedTime')) { + function blogspotDescSortWithPublishedTime($item1, $item2) + { + if ($item1['published']['$t'] === $item2['published']['$t']) { + return 0; + } + return ($item1['published']['$t'] < $item2['published']['$t']) ? 1 : -1; + } } -if ( ! function_exists('blogspotUSort')) { - function blogspotUSort($data) - { - usort($data, 'blogspotDescSortWithPublishedTime'); - return $data; - } +if (!function_exists('blogspotUSort')) { + function blogspotUSort($data) + { + usort($data, 'blogspotDescSortWithPublishedTime'); + return $data; + } } -if ( ! function_exists('blogspotFormatInformationItem')) { - function blogspotFormatInformationItem($blog) - { - if (isset($blog['media$thumbnail']['url'])) { - $blogThumb = trim($blog['media$thumbnail']['url']); - } else { - $blogThumb = 'https://c2.staticflickr.com/8/7858/32668285888_8da8a3c105_z.jpg'; - } - $blogThumb = str_replace( - array('/s72-c-d/', '/s72-c/', '/s72-d/', 'http://'), - array('/s320/', '/s320/', '/s320/', 'https://'), - $blogThumb - ); - $blogTitle = trim($blog['title']['$t']); - $cleanBlogTitle = strip_quotes($blogTitle); - $cleanBlogTitle = stripslashes($cleanBlogTitle); - $blogLink = ''; - foreach ($blog['link'] as $link) { - if ($link['rel'] === 'alternate') { - $blogLink .= $link['href']; - } else { - $blogLink .= ''; - } - } - $blogPublished = trim($blog['published']['$t']); - return array( - 'thumb' => $blogThumb, - 'name' => $blogTitle, - 'title' => $cleanBlogTitle, - 'url' => $blogLink, - 'published' => $blogPublished - ); - } +if (!function_exists('blogspotFormatInformationItem')) { + function blogspotFormatInformationItem($blog) + { + if (isset($blog['media$thumbnail']['url'])) { + $blogThumb = trim($blog['media$thumbnail']['url']); + } else { + $blogThumb = 'https://c2.staticflickr.com/8/7858/32668285888_8da8a3c105_z.jpg'; + } + $blogThumb = str_replace( + array('/s72-c-d/', '/s72-c/', '/s72-d/', 'http://'), + array('/s320/', '/s320/', '/s320/', 'https://'), + $blogThumb + ); + $blogTitle = trim($blog['title']['$t']); + $cleanBlogTitle = strip_quotes($blogTitle); + $cleanBlogTitle = stripslashes($cleanBlogTitle); + $blogLink = ''; + foreach ($blog['link'] as $link) { + if ($link['rel'] === 'alternate') { + $blogLink .= $link['href']; + } else { + $blogLink .= ''; + } + } + $blogPublished = trim($blog['published']['$t']); + return array( + 'thumb' => $blogThumb, + 'name' => $blogTitle, + 'title' => $cleanBlogTitle, + 'url' => $blogLink, + 'published' => $blogPublished + ); + } } diff --git a/helpers/byte_helper.php b/helpers/byte_helper.php index c271697..18a71a7 100644 --- a/helpers/byte_helper.php +++ b/helpers/byte_helper.php @@ -8,34 +8,34 @@ * Date: 30/07/2022 * Time: 15:50 */ -if ( ! function_exists('bytesHumanFormat')) { - /** - * Function bytesHumanFormat - * - * @param $size - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 30/07/2022 52:44 - */ - function bytesHumanFormat($size) - { - if ($size <= 0) { - return '0 bytes'; - } - if ($size === 1) { - return '1 byte'; - } - if ($size < 1024) { - return $size . ' bytes'; - } - $i = 0; - $iec = array('bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'); - while (($size / 1024) > 1) { - $size /= 1024; - ++$i; - } - return number_format($size, 2) . ' ' . $iec[$i]; - } +if (!function_exists('bytesHumanFormat')) { + /** + * Function bytesHumanFormat + * + * @param $size + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 30/07/2022 52:44 + */ + function bytesHumanFormat($size) + { + if ($size <= 0) { + return '0 bytes'; + } + if ($size === 1) { + return '1 byte'; + } + if ($size < 1024) { + return $size . ' bytes'; + } + $i = 0; + $iec = array('bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'); + while (($size / 1024) > 1) { + $size /= 1024; + ++$i; + } + return number_format($size, 2) . ' ' . $iec[$i]; + } } diff --git a/helpers/chart_render.php b/helpers/chart_render.php index f51159f..416c29e 100644 --- a/helpers/chart_render.php +++ b/helpers/chart_render.php @@ -8,15 +8,15 @@ * Date: 30/07/2022 * Time: 01:05 */ -if ( ! function_exists('bear_framework_default_get_data_chart')) { - function bear_framework_default_get_data_chart($item_list, $valueGet, $total) - { - return (new \nguyenanhung\CodeIgniter\BasicHelper\ChartRender())->get_data_chart($item_list, $valueGet, $total); - } +if (!function_exists('bear_framework_default_get_data_chart')) { + function bear_framework_default_get_data_chart($item_list, $valueGet, $total) + { + return (new \nguyenanhung\CodeIgniter\BasicHelper\ChartRender())->get_data_chart($item_list, $valueGet, $total); + } } -if ( ! function_exists('bear_framework_default_get_data_chart_report')) { - function bear_framework_default_get_data_chart_report($item_list, $valueGet) - { - return (new \nguyenanhung\CodeIgniter\BasicHelper\ChartRender())->get_data_chart_report($item_list, $valueGet); - } +if (!function_exists('bear_framework_default_get_data_chart_report')) { + function bear_framework_default_get_data_chart_report($item_list, $valueGet) + { + return (new \nguyenanhung\CodeIgniter\BasicHelper\ChartRender())->get_data_chart_report($item_list, $valueGet); + } } diff --git a/helpers/common_helper.php b/helpers/common_helper.php index 5e622f7..ea409a8 100644 --- a/helpers/common_helper.php +++ b/helpers/common_helper.php @@ -8,140 +8,140 @@ * Date: 09/11/2021 * Time: 09:17 */ -if ( ! function_exists('smart_bear_copyright_date')) { - function smart_bear_copyright_date($startYear = 2016) - { - return $startYear . '-' . date('Y'); - } +if (!function_exists('smart_bear_copyright_date')) { + function smart_bear_copyright_date($startYear = 2016) + { + return $startYear . '-' . date('Y'); + } } -if ( ! function_exists('smart_bear_copyright_line')) { - function smart_bear_copyright_line() - { - $helper = new \nguyenanhung\CodeIgniter\BasicHelper\BaseHelper(); - $author = $helper->getAuthor(); - return '© ' . $author['name'] . ''; - } +if (!function_exists('smart_bear_copyright_line')) { + function smart_bear_copyright_line() + { + $helper = new \nguyenanhung\CodeIgniter\BasicHelper\BaseHelper(); + $author = $helper->getAuthor(); + return '© ' . $author['name'] . ''; + } } -if ( ! function_exists('smart_bear_copyright_powered_line')) { - function smart_bear_copyright_powered_line() - { - $helper = new \nguyenanhung\CodeIgniter\BasicHelper\BaseHelper(); - $author = $helper->getAuthor(); - return 'Powered by ' . $author['name'] . ''; - } +if (!function_exists('smart_bear_copyright_powered_line')) { + function smart_bear_copyright_powered_line() + { + $helper = new \nguyenanhung\CodeIgniter\BasicHelper\BaseHelper(); + $author = $helper->getAuthor(); + return 'Powered by ' . $author['name'] . ''; + } } -if ( ! function_exists('smart_bear_basic_helper_version')) { - function smart_bear_basic_helper_version() - { - return \nguyenanhung\CodeIgniter\BasicHelper\BaseHelper::version(); - } +if (!function_exists('smart_bear_basic_helper_version')) { + function smart_bear_basic_helper_version() + { + return \nguyenanhung\CodeIgniter\BasicHelper\BaseHelper::version(); + } } -if ( ! function_exists('smart_bear_basic_helper_author')) { - function smart_bear_basic_helper_author() - { - $helper = new \nguyenanhung\CodeIgniter\BasicHelper\BaseHelper(); - return $helper->getAuthor(); - } +if (!function_exists('smart_bear_basic_helper_author')) { + function smart_bear_basic_helper_author() + { + $helper = new \nguyenanhung\CodeIgniter\BasicHelper\BaseHelper(); + return $helper->getAuthor(); + } } -if ( ! function_exists('isEmpty')) { - /** - * Function isEmpty - * - * @param mixed $input - * - * @return bool - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 10/07/2020 29:13 - */ - function isEmpty($input = '') - { - if ($input === null || $input === false || $input === '') { - return true; - } - $isset = isset($input); - if ($isset === true) { - $empty = empty($input); - if ($empty) { - return true; - } - return false; - } - return true; - } +if (!function_exists('isEmpty')) { + /** + * Function isEmpty + * + * @param mixed $input + * + * @return bool + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 10/07/2020 29:13 + */ + function isEmpty($input = '') + { + if ($input === null || $input === false || $input === '') { + return true; + } + $isset = isset($input); + if ($isset === true) { + $empty = empty($input); + if ($empty) { + return true; + } + return false; + } + return true; + } } -if ( ! function_exists('defaultCompressHtmlOutput')) { - /** - * Function defaultCompressHtmlOutput - * - * @param mixed $html - * - * @return array|string|string[]|null - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 26/12/2022 00:42 - */ - function defaultCompressHtmlOutput($html = '') - { - if (empty($html)) { - return $html; - } - $search = array( - '/\n/', // replace end of line by a space - '/\>[^\S ]+/s', // strip whitespaces after tags, except space - '/[^\S ]+\', '<', '\\1'); - return preg_replace($search, $replace, $html); - } +if (!function_exists('defaultCompressHtmlOutput')) { + /** + * Function defaultCompressHtmlOutput + * + * @param mixed $html + * + * @return array|string|string[]|null + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 26/12/2022 00:42 + */ + function defaultCompressHtmlOutput($html = '') + { + if (empty($html)) { + return $html; + } + $search = array( + '/\n/', // replace end of line by a space + '/\>[^\S ]+/s', // strip whitespaces after tags, except space + '/[^\S ]+\', '<', '\\1'); + return preg_replace($search, $replace, $html); + } } -if ( ! function_exists('generateRandomUniqueId')) { - function generateRandomUniqueId() - { - $uniqid = uniqid('-bear-', true); - $uniqid = trim(str_replace('.', '', $uniqid)); - return date('Ymd') . '-' . generate_uuid_v4() . $uniqid; - } +if (!function_exists('generateRandomUniqueId')) { + function generateRandomUniqueId() + { + $uniqid = uniqid('-bear-', true); + $uniqid = trim(str_replace('.', '', $uniqid)); + return date('Ymd') . '-' . generate_uuid_v4() . $uniqid; + } } -if ( ! function_exists('generateRandomNanoUniqueId')) { - function generateRandomNanoUniqueId() - { - $uniqid = uniqid('-bear-', true); - $uniqid = trim(str_replace('.', '', $uniqid)); - return date('Ymd') . '-' . randomNanoId(16) . $uniqid; - } +if (!function_exists('generateRandomNanoUniqueId')) { + function generateRandomNanoUniqueId() + { + $uniqid = uniqid('-bear-', true); + $uniqid = trim(str_replace('.', '', $uniqid)); + return date('Ymd') . '-' . randomNanoId(16) . $uniqid; + } } -if ( ! function_exists('__get_error_message__')) { - /** - * Function __get_error_message__ - * - * @param \Exception|\Throwable $e - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 29/03/2023 53:17 - */ - function __get_error_message__($e) - { - return "Error Code: " . $e->getCode() . " - File: " . $e->getFile() . " - Line: " . $e->getLine( - ) . " - Message: " . $e->getMessage(); - } +if (!function_exists('__get_error_message__')) { + /** + * Function __get_error_message__ + * + * @param \Exception|\Throwable $e + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 29/03/2023 53:17 + */ + function __get_error_message__($e) + { + return "Error Code: " . $e->getCode() . " - File: " . $e->getFile() . " - Line: " . $e->getLine( + ) . " - Message: " . $e->getMessage(); + } } -if ( ! function_exists('__get_error_trace__')) { - /** - * Function __get_error_trace__ - * - * @param \Exception|\Throwable $e - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 29/03/2023 53:48 - */ - function __get_error_trace__($e) - { - return "Error Trace: " . $e->getTraceAsString(); - } +if (!function_exists('__get_error_trace__')) { + /** + * Function __get_error_trace__ + * + * @param \Exception|\Throwable $e + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 29/03/2023 53:48 + */ + function __get_error_trace__($e) + { + return "Error Trace: " . $e->getTraceAsString(); + } } diff --git a/helpers/database_helper.php b/helpers/database_helper.php index ecf7c94..d71d8e9 100644 --- a/helpers/database_helper.php +++ b/helpers/database_helper.php @@ -8,37 +8,37 @@ * Date: 08/02/2023 * Time: 16:16 */ -if ( ! function_exists('generate_list_id_with_parent_id')) { - /** - * Function generate_list_id_with_parent_id - Tạo 1 list các ID, trong đó chứa các tập con phụ thuộc của ID đó - * - * VD: Dùng trong trường hợp muốn hiển thị nội dung của category cha và các category con trong cùng 1 page content - * - * @param array|object|mixed $allSubId - * @param string|int $parentId - * @param string $field - * - * @return array|string|int - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/02/2023 13:31 - */ - function generate_list_id_with_parent_id($allSubId, $parentId, $field = 'id') - { - if (is_array($allSubId) || is_object($allSubId)) { - // Xác định lấy toàn bộ tin tức ở các category con - $countSub = count($allSubId); // Đếm bảng ghi Category con - if ($countSub) { - // Nếu tồn tại các category con - $listSub = array(); - $listSub[] = $parentId; // Push category cha - foreach ($allSubId as $item) { - $itemId = is_array($item) ? $item[$field] : $item->$field; - $listSub[] = $itemId; // Push các category con vào mảng dữ liệu - } - return $listSub; - } - } - return $parentId; - } +if (!function_exists('generate_list_id_with_parent_id')) { + /** + * Function generate_list_id_with_parent_id - Tạo 1 list các ID, trong đó chứa các tập con phụ thuộc của ID đó + * + * VD: Dùng trong trường hợp muốn hiển thị nội dung của category cha và các category con trong cùng 1 page content + * + * @param array|object|mixed $allSubId + * @param string|int $parentId + * @param string $field + * + * @return array|string|int + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/02/2023 13:31 + */ + function generate_list_id_with_parent_id($allSubId, $parentId, $field = 'id') + { + if (is_array($allSubId) || is_object($allSubId)) { + // Xác định lấy toàn bộ tin tức ở các category con + $countSub = count($allSubId); // Đếm bảng ghi Category con + if ($countSub) { + // Nếu tồn tại các category con + $listSub = array(); + $listSub[] = $parentId; // Push category cha + foreach ($allSubId as $item) { + $itemId = is_array($item) ? $item[$field] : $item->$field; + $listSub[] = $itemId; // Push các category con vào mảng dữ liệu + } + return $listSub; + } + } + return $parentId; + } } diff --git a/helpers/date_helper.php b/helpers/date_helper.php index 1697eab..ae141f4 100644 --- a/helpers/date_helper.php +++ b/helpers/date_helper.php @@ -8,118 +8,118 @@ * Date: 10/05/2021 * Time: 04:11 */ -if ( ! function_exists('dayFloor')) { - /** - * Function dayFloor - * - * @param string $beginTime - * @param string $endTime - * - * @return int - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 10/05/2021 12:01 - */ - function dayFloor($beginTime = '', $endTime = '') - { - if (empty($beginTime) && empty($endTime)) { - return 0; - } - $floor = abs(strtotime($beginTime) - strtotime($endTime)); - return (int)floor($floor / (60 * 60 * 24)); - } +if (!function_exists('dayFloor')) { + /** + * Function dayFloor + * + * @param string $beginTime + * @param string $endTime + * + * @return int + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 10/05/2021 12:01 + */ + function dayFloor($beginTime = '', $endTime = '') + { + if (empty($beginTime) && empty($endTime)) { + return 0; + } + $floor = abs(strtotime($beginTime) - strtotime($endTime)); + return (int)floor($floor / (60 * 60 * 24)); + } } -if ( ! function_exists('getZuluTime')) { - /** - * Function getZuluTime - * - * @return string|null - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 16/06/2022 40:35 - */ - function getZuluTime() - { - try { - return (new DateTime("now", new DateTimeZone("UTC")))->format('Y-m-d\TH:i:s\Z'); - } catch (Exception $e) { - if (function_exists('log_message')) { - log_message('error', __get_error_message__($e)); - } - return null; - } - } +if (!function_exists('getZuluTime')) { + /** + * Function getZuluTime + * + * @return string|null + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 16/06/2022 40:35 + */ + function getZuluTime() + { + try { + return (new DateTime("now", new DateTimeZone("UTC")))->format('Y-m-d\TH:i:s\Z'); + } catch (Exception $e) { + if (function_exists('log_message')) { + log_message('error', __get_error_message__($e)); + } + return null; + } + } } -if ( ! function_exists('iso_8601_utc_time')) { - /** - * Function iso_8601_utc_time - * - * @return string|null - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 16/06/2022 41:19 - */ - function iso_8601_utc_time() - { - return getZuluTime(); - } +if (!function_exists('iso_8601_utc_time')) { + /** + * Function iso_8601_utc_time + * + * @return string|null + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 16/06/2022 41:19 + */ + function iso_8601_utc_time() + { + return getZuluTime(); + } } -if ( ! function_exists('getYesterday')) { - function getYesterday($format = 'Y-m-d') - { - return date($format, strtotime("-1 days")); - } +if (!function_exists('getYesterday')) { + function getYesterday($format = 'Y-m-d') + { + return date($format, strtotime("-1 days")); + } } -if ( ! function_exists('smart_bear_date_range')) { - function smart_bear_date_range($first, $last, $step = '+1 day', $format = 'Y-m-d') - { - $dates = array(); - $current = strtotime($first); - $last = strtotime($last); - while ($current <= $last) { - $dates[] = date($format, $current); - $current = strtotime($step, $current); - } - return $dates; - } +if (!function_exists('smart_bear_date_range')) { + function smart_bear_date_range($first, $last, $step = '+1 day', $format = 'Y-m-d') + { + $dates = array(); + $current = strtotime($first); + $last = strtotime($last); + while ($current <= $last) { + $dates[] = date($format, $current); + $current = strtotime($step, $current); + } + return $dates; + } } -if ( ! function_exists('format_datetime_vn')) { - function format_datetime_vn($datetime = '', $type = 'datetime') - { - if (empty($datetime)) { - if (array_key_exists('REQUEST_TIME', $_REQUEST)) { - $timestamp = $_REQUEST('REQUEST_TIME'); - } else { - $timestamp = time(); - } - } elseif ($type !== 'datetime') { - $timestamp = $datetime; - } else { - $timestamp = strtotime($datetime); - } - return date('d-m-Y H:i:s', $timestamp); - } +if (!function_exists('format_datetime_vn')) { + function format_datetime_vn($datetime = '', $type = 'datetime') + { + if (empty($datetime)) { + if (array_key_exists('REQUEST_TIME', $_REQUEST)) { + $timestamp = $_REQUEST('REQUEST_TIME'); + } else { + $timestamp = time(); + } + } elseif ($type !== 'datetime') { + $timestamp = $datetime; + } else { + $timestamp = strtotime($datetime); + } + return date('d-m-Y H:i:s', $timestamp); + } } -if ( ! function_exists('get_start_and_end_date_for_week')) { - /** - * Function get_start_and_end_date_for_week - * - * @param $week - * @param $year - * - * @return array - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 24/02/2023 22:06 - */ - function get_start_and_end_date_for_week($week, $year) - { - $time = strtotime("1 January $year", time()); - $day = date('w', $time); - $time += ((7 * $week) + 1 - $day) * 24 * 3600; - $return[0] = date('d-m-Y', $time); - $time += 6 * 24 * 3600; - $return[1] = date('d-m-Y', $time); - return $return; - } +if (!function_exists('get_start_and_end_date_for_week')) { + /** + * Function get_start_and_end_date_for_week + * + * @param $week + * @param $year + * + * @return array + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 24/02/2023 22:06 + */ + function get_start_and_end_date_for_week($week, $year) + { + $time = strtotime("1 January $year", time()); + $day = date('w', $time); + $time += ((7 * $week) + 1 - $day) * 24 * 3600; + $return[0] = date('d-m-Y', $time); + $time += 6 * 24 * 3600; + $return[1] = date('d-m-Y', $time); + return $return; + } } diff --git a/helpers/debug_helper.php b/helpers/debug_helper.php index 9b9f403..bd083a4 100644 --- a/helpers/debug_helper.php +++ b/helpers/debug_helper.php @@ -1,29 +1,29 @@ '; - array_map(static function ($var) { - var_dump($var); - }, func_get_args()); - die; - } +if (!function_exists('dd')) { + function dd($var) + { + echo '
';
+        array_map(static function ($var) {
+            var_dump($var);
+        }, func_get_args());
+        die;
+    }
 }
-if ( ! function_exists('ddd')) {
-	function ddd($str)
-	{
-		echo "
";
-		var_dump($str);
-		echo "
"; - die; - } +if (!function_exists('ddd')) { + function ddd($str) + { + echo "
";
+        var_dump($str);
+        echo "
"; + die; + } } -if ( ! function_exists('dump')) { - function dump($str = '') - { - echo "
";
-		print_r($str);
-		echo "
"; - } +if (!function_exists('dump')) { + function dump($str = '') + { + echo "
";
+        print_r($str);
+        echo "
"; + } } diff --git a/helpers/download_helper.php b/helpers/download_helper.php index a8dca70..213757d 100644 --- a/helpers/download_helper.php +++ b/helpers/download_helper.php @@ -8,100 +8,100 @@ * Date: 17/05/2023 * Time: 11:02 */ -if ( ! function_exists('download_file_chunked')) { - function download_file_chunked($path) - { - $file_name = basename($path); +if (!function_exists('download_file_chunked')) { + function download_file_chunked($path) + { + $file_name = basename($path); - // get the file's mime type to send the correct content type header - //$finfo = finfo_open(FILEINFO_MIME_TYPE); //For remote file, it may not work - //$mime_type = finfo_file($finfo, $path); //For remote file, it may not work - $mime_type = mime_type($file_name); + // get the file's mime type to send the correct content type header + //$finfo = finfo_open(FILEINFO_MIME_TYPE); //For remote file, it may not work + //$mime_type = finfo_file($finfo, $path); //For remote file, it may not work + $mime_type = mime_type($file_name); - $attachment = (mb_strstr($_SERVER['HTTP_USER_AGENT'], "MSIE")) ? "" : " attachment"; // IE 5.5 fix. + $attachment = (mb_strstr($_SERVER['HTTP_USER_AGENT'], "MSIE")) ? "" : " attachment"; // IE 5.5 fix. - // send the headers - header("Content-Type: $mime_type"); - header('Content-Transfer-Encoding: binary'); - //header('Content-Length: ' . filesize($path)); //PHP Warning: filesize(): stat failed for remote file - //header("Content-Disposition: attachment; filename=$file_name;"); - header("Content-Disposition: $attachment; filename=$file_name;"); + // send the headers + header("Content-Type: $mime_type"); + header('Content-Transfer-Encoding: binary'); + //header('Content-Length: ' . filesize($path)); //PHP Warning: filesize(): stat failed for remote file + //header("Content-Disposition: attachment; filename=$file_name;"); + header("Content-Disposition: $attachment; filename=$file_name;"); - $options = array( - "ssl" => array( - "verify_peer" => false, - "verify_peer_name" => false, - ), - ); + $options = array( + "ssl" => array( + "verify_peer" => false, + "verify_peer_name" => false, + ), + ); - $context = stream_context_create($options); + $context = stream_context_create($options); - //$handle = fopen($path, 'rb'); - $handle = fopen($path, 'rb', false, $context); + //$handle = fopen($path, 'rb'); + $handle = fopen($path, 'rb', false, $context); - ob_end_clean();//output buffering is disabled, so you won't hit your memory limit + ob_end_clean();//output buffering is disabled, so you won't hit your memory limit - $buffer = ''; - $chunkSize = 1024 * 1024; + $buffer = ''; + $chunkSize = 1024 * 1024; - //$newfname = basename($path); - //$newf = fopen ($newfname, "wb"); + //$newfname = basename($path); + //$newf = fopen ($newfname, "wb"); - ob_start(); - while ( ! feof($handle)) { - $buffer = fread($handle, $chunkSize); - echo $buffer; - ob_flush(); - flush(); - //fwrite($newf, $buffer, $chunkSize); - } + ob_start(); + while (!feof($handle)) { + $buffer = fread($handle, $chunkSize); + echo $buffer; + ob_flush(); + flush(); + //fwrite($newf, $buffer, $chunkSize); + } - fclose($handle); + fclose($handle); - //fclose($newf); + //fclose($newf); - exit; - } + exit; + } } -if ( ! function_exists('download_large_file')) { - function download_large_file($path) - { - // the file name of the download, change this if needed - $file_name = basename($path); +if (!function_exists('download_large_file')) { + function download_large_file($path) + { + // the file name of the download, change this if needed + $file_name = basename($path); - // get the file's mime type to send the correct content type header - //$finfo = finfo_open(FILEINFO_MIME_TYPE); //For remote file, it may not work - //$mime_type = finfo_file($finfo, $path); //For remote file, it may not work - $mime_type = mime_type($file_name); + // get the file's mime type to send the correct content type header + //$finfo = finfo_open(FILEINFO_MIME_TYPE); //For remote file, it may not work + //$mime_type = finfo_file($finfo, $path); //For remote file, it may not work + $mime_type = mime_type($file_name); - $attachment = (mb_strstr($_SERVER['HTTP_USER_AGENT'], "MSIE")) ? "" : " attachment"; // IE 5.5 fix. + $attachment = (mb_strstr($_SERVER['HTTP_USER_AGENT'], "MSIE")) ? "" : " attachment"; // IE 5.5 fix. - // send the headers - header("Content-Type: $mime_type"); - //header('Content-Length: ' . filesize($path)); //PHP Warning: filesize(): stat failed for remote file - //header("Content-Disposition: attachment; filename=$file_name;"); - header("Content-Disposition: $attachment; filename=$file_name;"); + // send the headers + header("Content-Type: $mime_type"); + //header('Content-Length: ' . filesize($path)); //PHP Warning: filesize(): stat failed for remote file + //header("Content-Disposition: attachment; filename=$file_name;"); + header("Content-Disposition: $attachment; filename=$file_name;"); - //Disable SSL verification - $options = array( - "ssl" => array( - "verify_peer" => false, - "verify_peer_name" => false, - ), - ); + //Disable SSL verification + $options = array( + "ssl" => array( + "verify_peer" => false, + "verify_peer_name" => false, + ), + ); - $context = stream_context_create($options); + $context = stream_context_create($options); - // stream the file - //$fp = fopen($path, 'rb'); - $fp = fopen($path, 'rb', false, $context); + // stream the file + //$fp = fopen($path, 'rb'); + $fp = fopen($path, 'rb', false, $context); - ob_end_clean();//output buffering is disabled, so you won't hit your memory limit + ob_end_clean();//output buffering is disabled, so you won't hit your memory limit - fpassthru($fp); + fpassthru($fp); - fclose($fp); + fclose($fp); - exit; - } + exit; + } } diff --git a/helpers/env_helper.php b/helpers/env_helper.php index 2f34997..cc07294 100644 --- a/helpers/env_helper.php +++ b/helpers/env_helper.php @@ -8,38 +8,38 @@ * Date: 30/07/2022 * Time: 15:47 */ -if ( ! function_exists('bear_get_env')) { - /** - * Function bear_get_env - * - * @param $a - * - * @return array|false|mixed|string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 30/07/2022 51:23 - */ - function bear_get_env($a) - { - if ( ! is_array($a)) { - $a = array($a); - } +if (!function_exists('bear_get_env')) { + /** + * Function bear_get_env + * + * @param $a + * + * @return array|false|mixed|string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 30/07/2022 51:23 + */ + function bear_get_env($a) + { + if (!is_array($a)) { + $a = array($a); + } - foreach ($a as $b) { - if (isset($_SERVER[$b])) { - return $_SERVER[$b]; - } - if (isset($_ENV[$b])) { - return $_ENV[$b]; - } - if (@getenv($b)) { - return @getenv($b); - } - if (function_exists('apache_getenv') && apache_getenv($b, true)) { - return apache_getenv($b, true); - } - } + foreach ($a as $b) { + if (isset($_SERVER[$b])) { + return $_SERVER[$b]; + } + if (isset($_ENV[$b])) { + return $_ENV[$b]; + } + if (@getenv($b)) { + return @getenv($b); + } + if (function_exists('apache_getenv') && apache_getenv($b, true)) { + return apache_getenv($b, true); + } + } - return ''; - } + return ''; + } } diff --git a/helpers/escape_helper.php b/helpers/escape_helper.php index d90e5de..7810799 100644 --- a/helpers/escape_helper.php +++ b/helpers/escape_helper.php @@ -8,15 +8,15 @@ * Date: 09/02/2023 * Time: 22:25 */ -if ( ! function_exists('bear_framework_basic_clean_str')) { - function bear_framework_basic_clean_str($str = '') - { - if (empty($str)) { - return $str; - } - $str = trim($str); - $str = strip_tags($str); - $str = htmlspecialchars($str, ENT_QUOTES | ENT_HTML5 | ENT_XHTML, 'UTF-8'); - return trim($str); - } +if (!function_exists('bear_framework_basic_clean_str')) { + function bear_framework_basic_clean_str($str = '') + { + if (empty($str)) { + return $str; + } + $str = trim($str); + $str = strip_tags($str); + $str = htmlspecialchars($str, ENT_QUOTES | ENT_HTML5 | ENT_XHTML, 'UTF-8'); + return trim($str); + } } diff --git a/helpers/facebook_helper.php b/helpers/facebook_helper.php index b3c9d6a..4b50cc9 100644 --- a/helpers/facebook_helper.php +++ b/helpers/facebook_helper.php @@ -8,112 +8,112 @@ * Date: 21/07/2022 * Time: 11:43 */ -if ( ! function_exists('widget_facebook_comments')) { - /** - * Function widget_facebook_comments - * - * @param string $url - * @param string $width - * @param int $num_posts - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 21/07/2022 48:16 - */ - function widget_facebook_comments($url = '', $width = '', $num_posts = 5) - { - return '
'; - } +if (!function_exists('widget_facebook_comments')) { + /** + * Function widget_facebook_comments + * + * @param string $url + * @param string $width + * @param int $num_posts + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 21/07/2022 48:16 + */ + function widget_facebook_comments($url = '', $width = '', $num_posts = 5) + { + return '
'; + } } -if ( ! function_exists('widget_facebook_share_button')) { - /** - * Function widget_facebook_share_button - * - * @param string $url - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 21/07/2022 45:46 - */ - function widget_facebook_share_button($url = '') - { - return '
'; - } +if (!function_exists('widget_facebook_share_button')) { + /** + * Function widget_facebook_share_button + * + * @param string $url + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 21/07/2022 45:46 + */ + function widget_facebook_share_button($url = '') + { + return '
'; + } } -if ( ! function_exists('widget_facebook_like_button')) { - /** - * Function widget_facebook_like_button - * - * @param string $url - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 21/07/2022 45:46 - */ - function widget_facebook_like_button($url = '') - { - return '
'; - } +if (!function_exists('widget_facebook_like_button')) { + /** + * Function widget_facebook_like_button + * + * @param string $url + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 21/07/2022 45:46 + */ + function widget_facebook_like_button($url = '') + { + return '
'; + } } -if ( ! function_exists('widget_facebook_save_button')) { - /** - * Function widget_facebook_save_button - * - * @param string $url - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 21/07/2022 45:46 - */ - function widget_facebook_save_button($url = '') - { - return '
'; - } +if (!function_exists('widget_facebook_save_button')) { + /** + * Function widget_facebook_save_button + * + * @param string $url + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 21/07/2022 45:46 + */ + function widget_facebook_save_button($url = '') + { + return '
'; + } } -if ( ! function_exists('widget_facebook_script_init')) { - /** - * Function widget_facebook_script_init - * - * @param string $appId - * @param string $version - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 21/07/2022 50:42 - */ - function widget_facebook_script_init($appId = '', $version = 'v14.0') - { - if (empty($version)) { - $version = 'v14.0'; - } - $url = 'https://connect.facebook.net/vi_VN/sdk.js#xfbml=1&version=' . trim($version) . '&appId=' . trim( - $appId - ) . '&autoLogAppEvents=1'; - return '
'; - } +if (!function_exists('widget_facebook_script_init')) { + /** + * Function widget_facebook_script_init + * + * @param string $appId + * @param string $version + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 21/07/2022 50:42 + */ + function widget_facebook_script_init($appId = '', $version = 'v14.0') + { + if (empty($version)) { + $version = 'v14.0'; + } + $url = 'https://connect.facebook.net/vi_VN/sdk.js#xfbml=1&version=' . trim($version) . '&appId=' . trim( + $appId + ) . '&autoLogAppEvents=1'; + return '
'; + } } -if ( ! function_exists('widget_facebook_div_init')) { - /** - * Function widget_facebook_div_init - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 30/07/2022 18:56 - */ - function widget_facebook_div_init() - { - return '
'; - } +if (!function_exists('widget_facebook_div_init')) { + /** + * Function widget_facebook_div_init + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 30/07/2022 18:56 + */ + function widget_facebook_div_init() + { + return '
'; + } } diff --git a/helpers/file_helper.php b/helpers/file_helper.php index 9914836..055bc3e 100644 --- a/helpers/file_helper.php +++ b/helpers/file_helper.php @@ -8,402 +8,402 @@ * Date: 09/11/2021 * Time: 09:20 */ -if ( ! function_exists('write_file')) { - /** - * Write File - * - * Writes data to the file specified in the path. - * Creates a new file if non-existent. - * - * @param string $path File path - * @param string $data Data to write - * @param string $mode fopen() mode (default: 'wb') - * - * @return bool - */ - function write_file($path, $data, $mode = 'wb') - { - if ( ! $fp = @fopen($path, $mode)) { - return false; - } - - flock($fp, LOCK_EX); - - for ($result = $written = 0, $length = mb_strlen($data); $written < $length; $written += $result) { - if (($result = fwrite($fp, mb_substr($data, $written))) === false) { - break; - } - } - - flock($fp, LOCK_UN); - fclose($fp); - - return is_int($result); - } +if (!function_exists('write_file')) { + /** + * Write File + * + * Writes data to the file specified in the path. + * Creates a new file if non-existent. + * + * @param string $path File path + * @param string $data Data to write + * @param string $mode fopen() mode (default: 'wb') + * + * @return bool + */ + function write_file($path, $data, $mode = 'wb') + { + if (!$fp = @fopen($path, $mode)) { + return false; + } + + flock($fp, LOCK_EX); + + for ($result = $written = 0, $length = mb_strlen($data); $written < $length; $written += $result) { + if (($result = fwrite($fp, mb_substr($data, $written))) === false) { + break; + } + } + + flock($fp, LOCK_UN); + fclose($fp); + + return is_int($result); + } } -if ( ! function_exists('delete_files')) { - /** - * Delete Files - * - * Deletes all files contained in the supplied directory path. - * Files must be writable or owned by the system in order to be deleted. - * If the second parameter is set to TRUE, any directories contained - * within the supplied base directory will be nuked as well. - * - * @param string $path File path - * @param bool $del_dir Whether to delete any directories found in the path - * @param bool $htdocs Whether to skip deleting .htaccess and index page files - * @param int $_level Current directory depth level (default: 0; internal use only) - * - * @return bool - */ - function delete_files($path, $del_dir = false, $htdocs = false, $_level = 0) - { - // Trim the trailing slash - $path = rtrim($path, '/\\'); - - if ( ! $current_dir = @opendir($path)) { - return false; - } - - while (false !== ($filename = @readdir($current_dir))) { - if ($filename !== '.' && $filename !== '..') { - $filepath = $path . DIRECTORY_SEPARATOR . $filename; - - if (is_dir($filepath) && ! is_link($filepath)) { - delete_files($filepath, $del_dir, $htdocs, $_level + 1); - } elseif ($htdocs !== true || ! preg_match( - '/^(\.htaccess|index\.(html|htm|php)|web\.config)$/i', - $filename - )) { - @unlink($filepath); - } - } - } - - closedir($current_dir); - - if (($del_dir === true && $_level > 0)) { - return @rmdir($path); - } - - return true; - } +if (!function_exists('delete_files')) { + /** + * Delete Files + * + * Deletes all files contained in the supplied directory path. + * Files must be writable or owned by the system in order to be deleted. + * If the second parameter is set to TRUE, any directories contained + * within the supplied base directory will be nuked as well. + * + * @param string $path File path + * @param bool $del_dir Whether to delete any directories found in the path + * @param bool $htdocs Whether to skip deleting .htaccess and index page files + * @param int $_level Current directory depth level (default: 0; internal use only) + * + * @return bool + */ + function delete_files($path, $del_dir = false, $htdocs = false, $_level = 0) + { + // Trim the trailing slash + $path = rtrim($path, '/\\'); + + if (!$current_dir = @opendir($path)) { + return false; + } + + while (false !== ($filename = @readdir($current_dir))) { + if ($filename !== '.' && $filename !== '..') { + $filepath = $path . DIRECTORY_SEPARATOR . $filename; + + if (is_dir($filepath) && !is_link($filepath)) { + delete_files($filepath, $del_dir, $htdocs, $_level + 1); + } elseif ($htdocs !== true || !preg_match( + '/^(\.htaccess|index\.(html|htm|php)|web\.config)$/i', + $filename + )) { + @unlink($filepath); + } + } + } + + closedir($current_dir); + + if (($del_dir === true && $_level > 0)) { + return @rmdir($path); + } + + return true; + } } -if ( ! function_exists('formatSizeUnits')) { - /** - * Function formatSizeUnits - * - * @param $bytes - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 09/11/2021 20:31 - */ - function formatSizeUnits($bytes) - { - if ($bytes >= 1073741824) { - $bytes = number_format($bytes / 1073741824, 2) . ' GB'; - } elseif ($bytes >= 1048576) { - $bytes = number_format($bytes / 1048576, 2) . ' MB'; - } elseif ($bytes >= 1024) { - $bytes = number_format($bytes / 1024, 2) . ' KB'; - } elseif ($bytes > 1) { - $bytes .= ' bytes'; - } elseif ($bytes === 1) { - $bytes .= ' byte'; - } else { - $bytes = '0 bytes'; - } - - return $bytes; - } +if (!function_exists('formatSizeUnits')) { + /** + * Function formatSizeUnits + * + * @param $bytes + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 09/11/2021 20:31 + */ + function formatSizeUnits($bytes) + { + if ($bytes >= 1073741824) { + $bytes = number_format($bytes / 1073741824, 2) . ' GB'; + } elseif ($bytes >= 1048576) { + $bytes = number_format($bytes / 1048576, 2) . ' MB'; + } elseif ($bytes >= 1024) { + $bytes = number_format($bytes / 1024, 2) . ' KB'; + } elseif ($bytes > 1) { + $bytes .= ' bytes'; + } elseif ($bytes === 1) { + $bytes .= ' byte'; + } else { + $bytes = '0 bytes'; + } + + return $bytes; + } } -if ( ! function_exists('genarateFileIndex')) { - /** - * Function genarateFileIndex - * - * @param string $file_path - * @param string $file_name - * - * @return bool - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 09/11/2021 55:13 - */ - function genarateFileIndex($file_path = '', $file_name = 'index.html') - { - if (function_exists('log_message') && function_exists('write_file')) { - if ($file_path !== '') { - if (is_dir($file_path) === false) { - if ( ! mkdir($file_path) && ! is_dir($file_path)) { - throw new RuntimeException(sprintf('Directory "%s" was not created', $file_path)); - } - log_message('debug', 'Genarate new Folder: ' . $file_path); - } - // SET file location - $file_location = $file_path . '/' . $file_name; - // Tạo file index.html nếu chưa có - if (file_exists($file_location) === false) { - $file_content = "\n\n\n403 Forbidden\n\n\n

Directory access is forbidden.

\n\n"; - write_file($file_location, $file_content); - log_message('debug', 'Genarate new file Index.html in Location ' . $file_location); - - return true; - } - log_message('debug', 'File Index.html Exists in Location ' . $file_location); - - return false; - } - log_message('debug', 'Genarate File Index.html failed'); - - return false; - } - - return false; - } +if (!function_exists('genarateFileIndex')) { + /** + * Function genarateFileIndex + * + * @param string $file_path + * @param string $file_name + * + * @return bool + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 09/11/2021 55:13 + */ + function genarateFileIndex($file_path = '', $file_name = 'index.html') + { + if (function_exists('log_message') && function_exists('write_file')) { + if ($file_path !== '') { + if (is_dir($file_path) === false) { + if (!mkdir($file_path) && !is_dir($file_path)) { + throw new RuntimeException(sprintf('Directory "%s" was not created', $file_path)); + } + log_message('debug', 'Genarate new Folder: ' . $file_path); + } + // SET file location + $file_location = $file_path . '/' . $file_name; + // Tạo file index.html nếu chưa có + if (file_exists($file_location) === false) { + $file_content = "\n\n\n403 Forbidden\n\n\n

Directory access is forbidden.

\n\n"; + write_file($file_location, $file_content); + log_message('debug', 'Genarate new file Index.html in Location ' . $file_location); + + return true; + } + log_message('debug', 'File Index.html Exists in Location ' . $file_location); + + return false; + } + log_message('debug', 'Genarate File Index.html failed'); + + return false; + } + + return false; + } } -if ( ! function_exists('genarateFileHtaccess')) { - /** - * Function genarateFileHtaccess - * - * @param string $file_path - * @param string $file_name - * - * @return bool - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 09/11/2021 55:51 - */ - function genarateFileHtaccess($file_path = '', $file_name = '.htaccess') - { - if (function_exists('log_message') && function_exists('write_file')) { - if ($file_path !== '') { - // SET file Path - if (is_dir($file_path) === false) { - if ( ! mkdir($file_path) && ! is_dir($file_path)) { - throw new RuntimeException(sprintf('Directory "%s" was not created', $file_path)); - } - log_message('debug', 'Genarate new Folder: ' . $file_path); - } - $file_location = $file_path . '/' . $file_name; - // Tạo file .htaccess nếu chưa có - if (file_exists($file_location) === false) { - $file_content = "RewriteEngine On\nOptions -Indexes\nAddType text/plain php3 php4 php5 php cgi asp aspx html css js"; - write_file($file_location, $file_content); - log_message('debug', 'Genarate new file .htaccess in Location ' . $file_location); - - return true; - } - log_message('debug', 'File .htaccess Exists in Location ' . $file_location); - - return false; - } - log_message('debug', 'Genarate File .htaccess failed'); - - return false; - } - - return false; - } +if (!function_exists('genarateFileHtaccess')) { + /** + * Function genarateFileHtaccess + * + * @param string $file_path + * @param string $file_name + * + * @return bool + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 09/11/2021 55:51 + */ + function genarateFileHtaccess($file_path = '', $file_name = '.htaccess') + { + if (function_exists('log_message') && function_exists('write_file')) { + if ($file_path !== '') { + // SET file Path + if (is_dir($file_path) === false) { + if (!mkdir($file_path) && !is_dir($file_path)) { + throw new RuntimeException(sprintf('Directory "%s" was not created', $file_path)); + } + log_message('debug', 'Genarate new Folder: ' . $file_path); + } + $file_location = $file_path . '/' . $file_name; + // Tạo file .htaccess nếu chưa có + if (file_exists($file_location) === false) { + $file_content = "RewriteEngine On\nOptions -Indexes\nAddType text/plain php3 php4 php5 php cgi asp aspx html css js"; + write_file($file_location, $file_content); + log_message('debug', 'Genarate new file .htaccess in Location ' . $file_location); + + return true; + } + log_message('debug', 'File .htaccess Exists in Location ' . $file_location); + + return false; + } + log_message('debug', 'Genarate File .htaccess failed'); + + return false; + } + + return false; + } } -if ( ! function_exists('genarateFileReadme')) { - /** - * Function genarateFileReadme - * - * @param string $file_path - * @param string $file_name - * - * @return bool - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 09/15/2021 58:14 - */ - function genarateFileReadme($file_path = '', $file_name = 'README.md') - { - if (function_exists('log_message') && function_exists('write_file')) { - if ($file_path !== '') { - if (is_dir($file_path) === false) { - if ( ! mkdir($file_path) && ! is_dir($file_path)) { - throw new RuntimeException(sprintf('Directory "%s" was not created', $file_path)); - } - log_message('debug', 'Genarate new Folder: ' . $file_path); - } - $file_location = $file_path . '/' . $file_name; - // Tạo file .htaccess nếu chưa có - if (file_exists($file_location) === false) { - $file_content = "# README"; - write_file($file_location, $file_content); - log_message('debug', 'Genarate new file ' . $file_name . ' in Location ' . $file_location); - - return true; - } - log_message('debug', 'File ' . $file_name . ' Exists in Location ' . $file_location); - - return false; - } - log_message('debug', 'Genarate File ' . $file_name . ' failed'); - - return false; - } - - return false; - } +if (!function_exists('genarateFileReadme')) { + /** + * Function genarateFileReadme + * + * @param string $file_path + * @param string $file_name + * + * @return bool + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 09/15/2021 58:14 + */ + function genarateFileReadme($file_path = '', $file_name = 'README.md') + { + if (function_exists('log_message') && function_exists('write_file')) { + if ($file_path !== '') { + if (is_dir($file_path) === false) { + if (!mkdir($file_path) && !is_dir($file_path)) { + throw new RuntimeException(sprintf('Directory "%s" was not created', $file_path)); + } + log_message('debug', 'Genarate new Folder: ' . $file_path); + } + $file_location = $file_path . '/' . $file_name; + // Tạo file .htaccess nếu chưa có + if (file_exists($file_location) === false) { + $file_content = "# README"; + write_file($file_location, $file_content); + log_message('debug', 'Genarate new file ' . $file_name . ' in Location ' . $file_location); + + return true; + } + log_message('debug', 'File ' . $file_name . ' Exists in Location ' . $file_location); + + return false; + } + log_message('debug', 'Genarate File ' . $file_name . ' failed'); + + return false; + } + + return false; + } } -if ( ! function_exists('makeNewFolder')) { - /** - * Function makeNewFolder - * - * @param string $folderPath - * - * @return bool - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 09/11/2021 57:33 - */ - function makeNewFolder($folderPath = '') - { - if (empty($folderPath)) { - return false; - } - if (is_dir($folderPath) === false) { - if ( ! mkdir($folderPath) && ! is_dir($folderPath)) { - throw new RuntimeException(sprintf('Directory "%s" was not created', $folderPath)); - } - genarateFileIndex($folderPath); - genarateFileHtaccess($folderPath); - genarateFileReadme($folderPath); - - return true; - } - - return false; - } +if (!function_exists('makeNewFolder')) { + /** + * Function makeNewFolder + * + * @param string $folderPath + * + * @return bool + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 09/11/2021 57:33 + */ + function makeNewFolder($folderPath = '') + { + if (empty($folderPath)) { + return false; + } + if (is_dir($folderPath) === false) { + if (!mkdir($folderPath) && !is_dir($folderPath)) { + throw new RuntimeException(sprintf('Directory "%s" was not created', $folderPath)); + } + genarateFileIndex($folderPath); + genarateFileHtaccess($folderPath); + genarateFileReadme($folderPath); + + return true; + } + + return false; + } } -if ( ! function_exists('new_folder')) { - /** - * Function new_folder - * - * @param string $folder - * - * @return bool - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 09/11/2021 58:13 - */ - function new_folder($folder = '') - { - return makeNewFolder($folder); - } +if (!function_exists('new_folder')) { + /** + * Function new_folder + * + * @param string $folder + * + * @return bool + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 09/11/2021 58:13 + */ + function new_folder($folder = '') + { + return makeNewFolder($folder); + } } -if ( ! function_exists('scan_folder')) { - /** - * Function scan_folder - Quét và lấy ra danh sách các thông tin dữ liệu trong folder - * - * @param $path - * @param $ignoreFiles - * - * @return array|false - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 12/12/2022 26:58 - */ - function scan_folder($path, $ignoreFiles = array()) - { - try { - if (is_dir($path)) { - $data = array_diff(scandir($path), array_merge(array('.', '..', '.DS_Store'), $ignoreFiles)); - natsort($data); - - return $data; - } - - return array(); - } catch (Exception $ex) { - if (function_exists('log_message')) { - log_message('error', __get_error_message__($ex)); - log_message('error', __get_error_trace__($ex)); - } - return array(); - } - } +if (!function_exists('scan_folder')) { + /** + * Function scan_folder - Quét và lấy ra danh sách các thông tin dữ liệu trong folder + * + * @param $path + * @param $ignoreFiles + * + * @return array|false + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 12/12/2022 26:58 + */ + function scan_folder($path, $ignoreFiles = array()) + { + try { + if (is_dir($path)) { + $data = array_diff(scandir($path), array_merge(array('.', '..', '.DS_Store'), $ignoreFiles)); + natsort($data); + + return $data; + } + + return array(); + } catch (Exception $ex) { + if (function_exists('log_message')) { + log_message('error', __get_error_message__($ex)); + log_message('error', __get_error_trace__($ex)); + } + return array(); + } + } } -if ( ! function_exists('getAllFileSizeInFolder')) { - /** - * Function getAllFileSizeInFolder - Get all File size in Folder - * - * @param $path - * - * @return float - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 12/12/2022 24:09 - */ - function getAllFileSizeInFolder($path) - { - $size = 0; - // Kiểm tra thư mục có tồn tại hay không - if (file_exists($path) && is_dir($path)) { - // Quét tất cả các file trong thư mục - $result = scandir($path); - - // Lọc ra các thư mục hiện tại (.) và các thư mục cha (..) - $files = array_diff($result, array('.', '..')); - - if (count($files) > 0) { - // Lặp qua mảng đã trả lại - foreach ($files as $file) { - if (is_file("$path/$file")) { - // tính tổng size - $size += filesize($path . '/' . $file); - } elseif (is_dir("$path/$file")) { - // Gọi đệ quy hàm nếu tìm thấy thư mục - getAllFileInFolder("$path/$file"); - } - } - } - } - - return round($size / 1024 / 1024, 2); - } +if (!function_exists('getAllFileSizeInFolder')) { + /** + * Function getAllFileSizeInFolder - Get all File size in Folder + * + * @param $path + * + * @return float + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 12/12/2022 24:09 + */ + function getAllFileSizeInFolder($path) + { + $size = 0; + // Kiểm tra thư mục có tồn tại hay không + if (file_exists($path) && is_dir($path)) { + // Quét tất cả các file trong thư mục + $result = scandir($path); + + // Lọc ra các thư mục hiện tại (.) và các thư mục cha (..) + $files = array_diff($result, array('.', '..')); + + if (count($files) > 0) { + // Lặp qua mảng đã trả lại + foreach ($files as $file) { + if (is_file("$path/$file")) { + // tính tổng size + $size += filesize($path . '/' . $file); + } elseif (is_dir("$path/$file")) { + // Gọi đệ quy hàm nếu tìm thấy thư mục + getAllFileInFolder("$path/$file"); + } + } + } + } + + return round($size / 1024 / 1024, 2); + } } -if ( ! function_exists('getAllFileInFolder')) { - /** - * Function getAllFileInFolder - Get all File in Folder - * - * @param $path - * - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 12/12/2022 23:53 - */ - function getAllFileInFolder($path) - { - // Kiểm tra thư mục có tồn tại hay không - if (file_exists($path) && is_dir($path)) { - // Quét tất cả các file trong thư mục - $result = scandir($path); - - // Lọc ra các thư mục hiện tại (.) và các thư mục cha (..) - $files = array_diff($result, array('.', '..')); - - if (count($files) > 0) { - // Lặp qua mảng đã trả lại - foreach ($files as $file) { - if (is_file("$path/$file")) { - // Hiển thị tên File - echo $file . "
"; - } elseif (is_dir("$path/$file")) { - // Gọi đệ quy hàm nếu tìm thấy thư mục - getAllFileInFolder("$path/$file"); - } - } - } else { - echo "ERROR: File not Found."; - } - } else { - echo "ERROR: Folder not Found."; - } - } +if (!function_exists('getAllFileInFolder')) { + /** + * Function getAllFileInFolder - Get all File in Folder + * + * @param $path + * + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 12/12/2022 23:53 + */ + function getAllFileInFolder($path) + { + // Kiểm tra thư mục có tồn tại hay không + if (file_exists($path) && is_dir($path)) { + // Quét tất cả các file trong thư mục + $result = scandir($path); + + // Lọc ra các thư mục hiện tại (.) và các thư mục cha (..) + $files = array_diff($result, array('.', '..')); + + if (count($files) > 0) { + // Lặp qua mảng đã trả lại + foreach ($files as $file) { + if (is_file("$path/$file")) { + // Hiển thị tên File + echo $file . "
"; + } elseif (is_dir("$path/$file")) { + // Gọi đệ quy hàm nếu tìm thấy thư mục + getAllFileInFolder("$path/$file"); + } + } + } else { + echo "ERROR: File not Found."; + } + } else { + echo "ERROR: Folder not Found."; + } + } } diff --git a/helpers/form_helper.php b/helpers/form_helper.php index 26a0061..775d73b 100644 --- a/helpers/form_helper.php +++ b/helpers/form_helper.php @@ -8,30 +8,30 @@ * Date: 24/02/2023 * Time: 00:00 */ -if ( ! function_exists('join_value_multiple')) { - /** - * Join value multiple - * - * @param $str - * - * @return string - */ - function join_value_multiple($str) - { - $num = count($str); - $max = $num - 1; - $string = ""; +if (!function_exists('join_value_multiple')) { + /** + * Join value multiple + * + * @param $str + * + * @return string + */ + function join_value_multiple($str) + { + $num = count($str); + $max = $num - 1; + $string = ""; - for ($i = 0; $i < $num; $i++) { - $string = $i < $max ? $string . $str[$i] . ',' : $string . $str[$i]; - } + for ($i = 0; $i < $num; $i++) { + $string = $i < $max ? $string . $str[$i] . ',' : $string . $str[$i]; + } - unset($i); + unset($i); - if ($string === '') { - return '0'; - } + if ($string === '') { + return '0'; + } - return $string; - } + return $string; + } } diff --git a/helpers/gravatar_helper.php b/helpers/gravatar_helper.php index fef23d9..36203e2 100644 --- a/helpers/gravatar_helper.php +++ b/helpers/gravatar_helper.php @@ -8,53 +8,53 @@ * Date: 20/01/2023 * Time: 00:30 */ -if ( ! function_exists('bear_framework_gravatar_init')) { - /** - * Function bear_framework_gravatar_init - * - * @param $username - * - * @return mixed|string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 20/01/2023 36:48 - */ - function bear_framework_gravatar_init($username = 'nguyenanhung') - { - if ( ! function_exists('config_item') || ! function_exists('get_instance')) { - return ''; - } +if (!function_exists('bear_framework_gravatar_init')) { + /** + * Function bear_framework_gravatar_init + * + * @param $username + * + * @return mixed|string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 20/01/2023 36:48 + */ + function bear_framework_gravatar_init($username = 'nguyenanhung') + { + if (!function_exists('config_item') || !function_exists('get_instance')) { + return ''; + } - $url = 'https://vi.gravatar.com/' . trim($username) . '.json'; - $file = md5($url); + $url = 'https://vi.gravatar.com/' . trim($username) . '.json'; + $file = md5($url); - $cms = &get_instance(); - $cms->load->driver('cache', array('adapter' => 'file', 'backup' => 'dummy')); - if ( ! $res = $cms->cache->get($file)) { - $respond = sendSimpleGetRequest($url); - $res = json_decode($respond, false); - $cms->cache->save($file, $res, 86400); - } + $cms = &get_instance(); + $cms->load->driver('cache', array('adapter' => 'file', 'backup' => 'dummy')); + if (!$res = $cms->cache->get($file)) { + $respond = sendSimpleGetRequest($url); + $res = json_decode($respond, false); + $cms->cache->save($file, $res, 86400); + } - return $res; - } + return $res; + } } -if ( ! function_exists('bear_framework_show_gravatar')) { - /** - * Function bear_framework_show_gravatar - * - * @param $username - * @param $size - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 20/01/2023 37:08 - */ - function bear_framework_show_gravatar($username = 'nguyenanhung', $size = 300) - { - return bear_framework_gravatar_init($username)->entry[0]->thumbnailUrl . '?' . http_build_query( - array('size' => $size) - ); - } +if (!function_exists('bear_framework_show_gravatar')) { + /** + * Function bear_framework_show_gravatar + * + * @param $username + * @param $size + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 20/01/2023 37:08 + */ + function bear_framework_show_gravatar($username = 'nguyenanhung', $size = 300) + { + return bear_framework_gravatar_init($username)->entry[0]->thumbnailUrl . '?' . http_build_query( + array('size' => $size) + ); + } } diff --git a/helpers/html_helper.php b/helpers/html_helper.php index f23b82b..3e56479 100644 --- a/helpers/html_helper.php +++ b/helpers/html_helper.php @@ -8,168 +8,168 @@ * Date: 09/11/2021 * Time: 08:59 */ -if ( ! function_exists('meta_dns_prefetch')) { - /** - * Function meta_dns_prefetch - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 12/10/2020 31:33 - */ - function meta_dns_prefetch() - { - return "\n\n\n\n\n\n"; - } +if (!function_exists('meta_dns_prefetch')) { + /** + * Function meta_dns_prefetch + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 12/10/2020 31:33 + */ + function meta_dns_prefetch() + { + return "\n\n\n\n\n\n"; + } } -if ( ! function_exists('meta_property')) { - /** - * Function meta_property - * - * @param string|array $property - * @param string $content - * @param string $type - * @param string $newline - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 12/10/2020 31:45 - */ - function meta_property($property = '', $content = '', $type = 'property', $newline = "\n") - { - // Since we allow the data to be passes as a string, a simple array - // or a multidimensional one, we need to do a little prepping. - if ( ! is_array($property)) { - $property = array( - array( - 'property' => $property, - 'content' => $content, - 'type' => $type, - 'newline' => $newline - ) - ); - } elseif (isset($property['property'])) { - // Turn single array into multidimensional - $property = array($property); - } - $str = ''; - foreach ($property as $meta) { - $type = (isset($meta['type']) && $meta['type'] !== 'property') ? 'itemprop' : 'property'; - $property = isset($meta['property']) ? $meta['property'] : ''; - $content = isset($meta['content']) ? $meta['content'] : ''; - $newline = isset($meta['newline']) ? $meta['newline'] : "\n"; - $str .= '' . $newline; - } +if (!function_exists('meta_property')) { + /** + * Function meta_property + * + * @param string|array $property + * @param string $content + * @param string $type + * @param string $newline + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 12/10/2020 31:45 + */ + function meta_property($property = '', $content = '', $type = 'property', $newline = "\n") + { + // Since we allow the data to be passes as a string, a simple array + // or a multidimensional one, we need to do a little prepping. + if (!is_array($property)) { + $property = array( + array( + 'property' => $property, + 'content' => $content, + 'type' => $type, + 'newline' => $newline + ) + ); + } elseif (isset($property['property'])) { + // Turn single array into multidimensional + $property = array($property); + } + $str = ''; + foreach ($property as $meta) { + $type = (isset($meta['type']) && $meta['type'] !== 'property') ? 'itemprop' : 'property'; + $property = isset($meta['property']) ? $meta['property'] : ''; + $content = isset($meta['content']) ? $meta['content'] : ''; + $newline = isset($meta['newline']) ? $meta['newline'] : "\n"; + $str .= '' . $newline; + } - return $str; - } + return $str; + } } -if ( ! function_exists('tachPage')) { - /** - * Function tachPage - * - * @param $input - * - * @return mixed - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 12/10/2020 31:55 - */ - function tachPage($input) - { - if (empty($input)) { - return $input; - } - preg_match('/(.*)-c(.*).html/U', $input, $output); +if (!function_exists('tachPage')) { + /** + * Function tachPage + * + * @param $input + * + * @return mixed + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 12/10/2020 31:55 + */ + function tachPage($input) + { + if (empty($input)) { + return $input; + } + preg_match('/(.*)-c(.*).html/U', $input, $output); - return $output[1]; - } + return $output[1]; + } } -if ( ! function_exists('stripHtmlTag')) { - /** - * Function stripHtmlTag - * - * @param $str - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 12/10/2020 32:06 - */ - function stripHtmlTag($str) - { - if (empty($str)) { - return $str; - } - $regEx = '/([^<]*<\s*[a-z](?:[0-9]|[a-z]{0,9}))(?:(?:\s*[a-z\-]{2,14}\s*=\s*(?:"[^"]*"|\'[^\']*\'))*)(\s*\/?>[^<]*)/i'; - $chunks = preg_split($regEx, $str, -1, PREG_SPLIT_DELIM_CAPTURE); - $chunkCount = count($chunks); - $strippedString = ''; - for ($n = 1; $n < $chunkCount; $n++) { - $strippedString .= $chunks[$n]; - } +if (!function_exists('stripHtmlTag')) { + /** + * Function stripHtmlTag + * + * @param $str + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 12/10/2020 32:06 + */ + function stripHtmlTag($str) + { + if (empty($str)) { + return $str; + } + $regEx = '/([^<]*<\s*[a-z](?:[0-9]|[a-z]{0,9}))(?:(?:\s*[a-z\-]{2,14}\s*=\s*(?:"[^"]*"|\'[^\']*\'))*)(\s*\/?>[^<]*)/i'; + $chunks = preg_split($regEx, $str, -1, PREG_SPLIT_DELIM_CAPTURE); + $chunkCount = count($chunks); + $strippedString = ''; + for ($n = 1; $n < $chunkCount; $n++) { + $strippedString .= $chunks[$n]; + } - return $strippedString; - } + return $strippedString; + } } -if ( ! function_exists('strip_only_tags')) { - /** - * Function strip_only_tags - * - * @param $str - * @param $tags - * @param bool $stripContent - * - * @return string|string[]|null - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 12/10/2020 32:14 - */ - function strip_only_tags($str, $tags, $stripContent = false) - { - if (empty($str)) { - return $str; - } +if (!function_exists('strip_only_tags')) { + /** + * Function strip_only_tags + * + * @param $str + * @param $tags + * @param bool $stripContent + * + * @return string|string[]|null + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 12/10/2020 32:14 + */ + function strip_only_tags($str, $tags, $stripContent = false) + { + if (empty($str)) { + return $str; + } - $content = ''; + $content = ''; - if ( ! is_array($tags)) { - $tags = (mb_strpos($str, '>') !== false ? explode('>', str_replace('<', '', $tags)) : array($tags)); - if (end($tags) === '') { - array_pop($tags); - } - } + if (!is_array($tags)) { + $tags = (mb_strpos($str, '>') !== false ? explode('>', str_replace('<', '', $tags)) : array($tags)); + if (end($tags) === '') { + array_pop($tags); + } + } - foreach ($tags as $tag) { - if ($stripContent) { - $content = '(.+|\s[^>]*>)|)'; - } + foreach ($tags as $tag) { + if ($stripContent) { + $content = '(.+|\s[^>]*>)|)'; + } - $str = preg_replace('#|\s[^>]*>)' . $content . '#is', '', $str); - } + $str = preg_replace('#|\s[^>]*>)' . $content . '#is', '', $str); + } - return $str; - } + return $str; + } } -if ( ! function_exists('tracking_google_analytics')) { - /** - * Function tracking_google_analytics - * - * @param string $analytics_id - * @param string $analytics_mode - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 12/10/2020 32:22 - */ - function tracking_google_analytics($analytics_id = '', $analytics_mode = 'auto') - { - if (empty($analytics_id)) { - return $analytics_id; - } - $html = ""; - return trim($html); - } + return trim($html); + } } -if ( ! function_exists('tracking_google_gtag_analytics_default')) { - /** - * Function tracking_google_gtag_analytics_default - * - * @param string $ID - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 30/07/2022 15:59 - */ - function tracking_google_gtag_analytics_default($ID = '') - { - if (empty($ID)) { - return $ID; - } - $html = "" . PHP_EOL; - $html .= "" . PHP_EOL; - $html .= "" . PHP_EOL; + $html .= ""; - return $html; - } + return $html; + } } -if ( ! function_exists('html_tag')) { - /** - * Create a XHTML tag - * - * @param string $tag The tag name - * @param array|string $attr The tag attributes - * @param string|bool $content The content to place in the tag, or false for no closing tag - * - * @return string - */ - function html_tag($tag, $attr = array(), $content = false) - { - // list of void elements (tags that can not have content) - static $void_elements = array( - // html4 - "area", - "base", - "br", - "col", - "hr", - "img", - "input", - "link", - "meta", - "param", - // html5 - "command", - "embed", - "keygen", - "source", - "track", - "wbr", - // html5.1 - "menuitem", - ); +if (!function_exists('html_tag')) { + /** + * Create a XHTML tag + * + * @param string $tag The tag name + * @param array|string $attr The tag attributes + * @param string|bool $content The content to place in the tag, or false for no closing tag + * + * @return string + */ + function html_tag($tag, $attr = array(), $content = false) + { + // list of void elements (tags that can not have content) + static $void_elements = array( + // html4 + "area", + "base", + "br", + "col", + "hr", + "img", + "input", + "link", + "meta", + "param", + // html5 + "command", + "embed", + "keygen", + "source", + "track", + "wbr", + // html5.1 + "menuitem", + ); - // construct the HTML - $html = '<' . $tag; - $html .= ( ! empty($attr)) ? ' ' . (is_array($attr) ? arrayToAttributes($attr) : $attr) : ''; + // construct the HTML + $html = '<' . $tag; + $html .= (!empty($attr)) ? ' ' . (is_array($attr) ? arrayToAttributes($attr) : $attr) : ''; - // a void element? - if (in_array(mb_strtolower($tag), $void_elements)) { - // these can not have content - $html .= ' />'; - } else { - // add the content and close the tag - $html .= '>' . $content . ''; - } + // a void element? + if (in_array(mb_strtolower($tag), $void_elements)) { + // these can not have content + $html .= ' />'; + } else { + // add the content and close the tag + $html .= '>' . $content . ''; + } - return $html; - } + return $html; + } } -if ( ! function_exists('bear_framework_show_jsonld_script')) { - function bear_framework_show_jsonld_script($content) - { - $content = trim($content); - if (empty($content)) { - return $content; - } - $start = ''; - return $start . PHP_EOL . $content . PHP_EOL . $end; - } +if (!function_exists('bear_framework_show_jsonld_script')) { + function bear_framework_show_jsonld_script($content) + { + $content = trim($content); + if (empty($content)) { + return $content; + } + $start = ''; + return $start . PHP_EOL . $content . PHP_EOL . $end; + } } diff --git a/helpers/image_helper.php b/helpers/image_helper.php index a57b2e3..edac71b 100644 --- a/helpers/image_helper.php +++ b/helpers/image_helper.php @@ -8,145 +8,145 @@ * Date: 08/07/2021 * Time: 01:07 */ -if ( ! function_exists('google_image_resize')) { - /** - * Function google_image_resize - * - * @param string $url - * @param int|null $width - * @param int|null $height - * @param string|null $server - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 07/27/2021 37:48 - */ - function google_image_resize($url = '', $width = 100, $height = null, $server = 'images1') - { - return nguyenanhung\CodeIgniter\BasicHelper\ImageHelper::googleGadgetsProxy($url, $width, $height, $server); - } +if (!function_exists('google_image_resize')) { + /** + * Function google_image_resize + * + * @param string $url + * @param int|null $width + * @param int|null $height + * @param string|null $server + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 07/27/2021 37:48 + */ + function google_image_resize($url = '', $width = 100, $height = null, $server = 'images1') + { + return nguyenanhung\CodeIgniter\BasicHelper\ImageHelper::googleGadgetsProxy($url, $width, $height, $server); + } } -if ( ! function_exists('google_image_proxy_dns_prefetch')) { - /** - * Function google_image_proxy_dns_prefetch - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 09/15/2021 36:03 - */ - function google_image_proxy_dns_prefetch() - { - return nguyenanhung\CodeIgniter\BasicHelper\ImageHelper::googleGadgetsProxyDnsPrefetch(); - } +if (!function_exists('google_image_proxy_dns_prefetch')) { + /** + * Function google_image_proxy_dns_prefetch + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 09/15/2021 36:03 + */ + function google_image_proxy_dns_prefetch() + { + return nguyenanhung\CodeIgniter\BasicHelper\ImageHelper::googleGadgetsProxyDnsPrefetch(); + } } -if ( ! function_exists('wordpress_proxy')) { - /** - * Function wordpress_proxy - * - * @param string $imageUrl - * @param string $server - * @param int|string|null $width - * @param int|string|null $height - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 07/27/2021 38:04 - */ - function wordpress_proxy($imageUrl = '', $server = 'i3', $width = null, $height = null) - { - return nguyenanhung\CodeIgniter\BasicHelper\ImageHelper::wordpressProxy($imageUrl, $server, $width, $height); - } +if (!function_exists('wordpress_proxy')) { + /** + * Function wordpress_proxy + * + * @param string $imageUrl + * @param string $server + * @param int|string|null $width + * @param int|string|null $height + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 07/27/2021 38:04 + */ + function wordpress_proxy($imageUrl = '', $server = 'i3', $width = null, $height = null) + { + return nguyenanhung\CodeIgniter\BasicHelper\ImageHelper::wordpressProxy($imageUrl, $server, $width, $height); + } } -if ( ! function_exists('wordpress_proxy_dns_prefetch')) { - /** - * Function wordpress_proxy_dns_prefetch - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 09/15/2021 36:15 - */ - function wordpress_proxy_dns_prefetch() - { - return nguyenanhung\CodeIgniter\BasicHelper\ImageHelper::wordpressProxyDnsPrefetch(); - } +if (!function_exists('wordpress_proxy_dns_prefetch')) { + /** + * Function wordpress_proxy_dns_prefetch + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 09/15/2021 36:15 + */ + function wordpress_proxy_dns_prefetch() + { + return nguyenanhung\CodeIgniter\BasicHelper\ImageHelper::wordpressProxyDnsPrefetch(); + } } -if ( ! function_exists('bear_framework_image_url')) { - /** - * Function bear_framework_image_url - * - * @param $input - * @param $server - * @param $base - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 15/06/2022 54:18 - */ - function bear_framework_image_url($input = '', $server = '', $base = 'live') - { - return nguyenanhung\CodeIgniter\BasicHelper\ImageHelper::formatImageUrl($input, $server, $base); - } +if (!function_exists('bear_framework_image_url')) { + /** + * Function bear_framework_image_url + * + * @param $input + * @param $server + * @param $base + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 15/06/2022 54:18 + */ + function bear_framework_image_url($input = '', $server = '', $base = 'live') + { + return nguyenanhung\CodeIgniter\BasicHelper\ImageHelper::formatImageUrl($input, $server, $base); + } } -if ( ! function_exists('bear_framework_create_image_thumbnail')) { - /** - * Function bear_framework_create_image_thumbnail - * - * @param $url - * @param $width - * @param $height - * - * @return string|null - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 15/09/2023 57:40 - */ - function bear_framework_create_image_thumbnail($url = '', $width = 100, $height = 100) - { - return create_image_thumbnail($url, $width, $height); - } +if (!function_exists('bear_framework_create_image_thumbnail')) { + /** + * Function bear_framework_create_image_thumbnail + * + * @param $url + * @param $width + * @param $height + * + * @return string|null + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 15/09/2023 57:40 + */ + function bear_framework_create_image_thumbnail($url = '', $width = 100, $height = 100) + { + return create_image_thumbnail($url, $width, $height); + } } -if ( ! function_exists('create_image_thumbnail')) { - /** - * Function create_image_thumbnail - * - * @param $url - * @param $width - * @param $height - * - * @return string|null - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 15/09/2023 50:33 - */ - function create_image_thumbnail($url = '', $width = 100, $height = 100) - { - return nguyenanhung\CodeIgniter\BasicHelper\ImageHelper::createThumbnail($url, $width, $height); - } +if (!function_exists('create_image_thumbnail')) { + /** + * Function create_image_thumbnail + * + * @param $url + * @param $width + * @param $height + * + * @return string|null + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 15/09/2023 50:33 + */ + function create_image_thumbnail($url = '', $width = 100, $height = 100) + { + return nguyenanhung\CodeIgniter\BasicHelper\ImageHelper::createThumbnail($url, $width, $height); + } } -if ( ! function_exists('bear_framework_create_image_thumbnail_with_cache')) { - /** - * Function bear_framework_create_image_thumbnail_with_cache - * - * @param $url - * @param $width - * @param $height - * - * @return mixed|string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 25/02/2023 27:49 - */ - function bear_framework_create_image_thumbnail_with_cache($url = '', $width = 100, $height = 100) - { - return nguyenanhung\CodeIgniter\BasicHelper\ImageHelper::createThumbnailWithCodeIgniterCache( - $url, - $width, - $height - ); - } +if (!function_exists('bear_framework_create_image_thumbnail_with_cache')) { + /** + * Function bear_framework_create_image_thumbnail_with_cache + * + * @param $url + * @param $width + * @param $height + * + * @return mixed|string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 25/02/2023 27:49 + */ + function bear_framework_create_image_thumbnail_with_cache($url = '', $width = 100, $height = 100) + { + return nguyenanhung\CodeIgniter\BasicHelper\ImageHelper::createThumbnailWithCodeIgniterCache( + $url, + $width, + $height + ); + } } diff --git a/helpers/index.html b/helpers/index.html index a2c44cc..408c9de 100644 --- a/helpers/index.html +++ b/helpers/index.html @@ -1,7 +1,7 @@ - 403 Forbidden + 403 Forbidden

Directory access is forbidden.

diff --git a/helpers/ip_helper.php b/helpers/ip_helper.php index b10c060..f644d37 100644 --- a/helpers/ip_helper.php +++ b/helpers/ip_helper.php @@ -8,257 +8,257 @@ * Date: 08/07/2021 * Time: 01:09 */ -if ( ! function_exists('getIPAddress')) { - /** - * Function getIPAddress - * - * @param bool $convertToInteger - * - * @return bool|int|string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 10/09/2020 59:22 - */ - function getIPAddress($convertToInteger = false) - { - $ipKeys = array( - 0 => 'HTTP_CF_CONNECTING_IP', - 1 => 'HTTP_X_FORWARDED_FOR', - 2 => 'HTTP_X_FORWARDED', - 3 => 'HTTP_X_IPADDRESS', - 4 => 'HTTP_X_CLUSTER_CLIENT_IP', - 5 => 'HTTP_FORWARDED_FOR', - 6 => 'HTTP_FORWARDED', - 7 => 'HTTP_CLIENT_IP', - 8 => 'HTTP_IP', - 9 => 'REMOTE_ADDR' - ); +if (!function_exists('getIPAddress')) { + /** + * Function getIPAddress + * + * @param bool $convertToInteger + * + * @return bool|int|string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 10/09/2020 59:22 + */ + function getIPAddress($convertToInteger = false) + { + $ipKeys = array( + 0 => 'HTTP_CF_CONNECTING_IP', + 1 => 'HTTP_X_FORWARDED_FOR', + 2 => 'HTTP_X_FORWARDED', + 3 => 'HTTP_X_IPADDRESS', + 4 => 'HTTP_X_CLUSTER_CLIENT_IP', + 5 => 'HTTP_FORWARDED_FOR', + 6 => 'HTTP_FORWARDED', + 7 => 'HTTP_CLIENT_IP', + 8 => 'HTTP_IP', + 9 => 'REMOTE_ADDR' + ); - foreach ($ipKeys as $key) { - if (array_key_exists($key, $_SERVER) === true) { - foreach (explode(',', $_SERVER[$key]) as $ip) { - $ip = trim($ip); - if ($convertToInteger === true) { - return ip2long($ip); - } + foreach ($ipKeys as $key) { + if (array_key_exists($key, $_SERVER) === true) { + foreach (explode(',', $_SERVER[$key]) as $ip) { + $ip = trim($ip); + if ($convertToInteger === true) { + return ip2long($ip); + } - return $ip; - } - } - } + return $ip; + } + } + } - if (isset($_SERVER['SERVER_NAME']) && $_SERVER['SERVER_NAME'] === 'localhost') { - return '127.0.0.1'; - } + if (isset($_SERVER['SERVER_NAME']) && $_SERVER['SERVER_NAME'] === 'localhost') { + return '127.0.0.1'; + } - return false; - } + return false; + } } -if ( ! function_exists('getIPAddressByHaProxy')) { - /** - * Function getIPAddressByHaProxy - * - * @param bool $convertToInteger - * - * @return bool|int|string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 10/09/2020 59:22 - */ - function getIPAddressByHaProxy($convertToInteger = false) - { - $key = 'HTTP_X_FORWARDED_FOR'; - if (array_key_exists($key, $_SERVER) === true) { - foreach (explode(',', $_SERVER[$key]) as $ip) { - $ip = trim($ip); - if ($this->ipValidate($ip)) { - if ($convertToInteger === true) { - return ip2long($ip); - } +if (!function_exists('getIPAddressByHaProxy')) { + /** + * Function getIPAddressByHaProxy + * + * @param bool $convertToInteger + * + * @return bool|int|string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 10/09/2020 59:22 + */ + function getIPAddressByHaProxy($convertToInteger = false) + { + $key = 'HTTP_X_FORWARDED_FOR'; + if (array_key_exists($key, $_SERVER) === true) { + foreach (explode(',', $_SERVER[$key]) as $ip) { + $ip = trim($ip); + if ($this->ipValidate($ip)) { + if ($convertToInteger === true) { + return ip2long($ip); + } - return $ip; - } - } - } - if (isset($_SERVER['SERVER_NAME']) && $_SERVER['SERVER_NAME'] === 'localhost') { - return '127.0.0.1'; - } + return $ip; + } + } + } + if (isset($_SERVER['SERVER_NAME']) && $_SERVER['SERVER_NAME'] === 'localhost') { + return '127.0.0.1'; + } - return false; - } + return false; + } } -if ( ! function_exists('get_ip_by_ha_proxy')) { - /** - * Function get_ip_by_ha_proxy - * - * @param bool $convertToInteger - * - * @return bool|int|string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 10/09/2020 59:22 - */ - function get_ip_by_ha_proxy($convertToInteger = false) - { - return getIPAddressByHaProxy($convertToInteger); - } +if (!function_exists('get_ip_by_ha_proxy')) { + /** + * Function get_ip_by_ha_proxy + * + * @param bool $convertToInteger + * + * @return bool|int|string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 10/09/2020 59:22 + */ + function get_ip_by_ha_proxy($convertToInteger = false) + { + return getIPAddressByHaProxy($convertToInteger); + } } -if ( ! function_exists('get_ip_address_2017')) { - /** - * Function get_ip_address_2017 - * - * @param bool $convertToInteger - * - * @return bool|int|string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 10/09/2020 59:22 - */ - function get_ip_address_2017($convertToInteger = false) - { - return getIPAddress($convertToInteger); - } +if (!function_exists('get_ip_address_2017')) { + /** + * Function get_ip_address_2017 + * + * @param bool $convertToInteger + * + * @return bool|int|string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 10/09/2020 59:22 + */ + function get_ip_address_2017($convertToInteger = false) + { + return getIPAddress($convertToInteger); + } } -if ( ! function_exists('get_ip_address')) { - /** - * Function get_ip_address - * - * @param bool $convertToInteger - * - * @return bool|int|string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 10/09/2020 59:22 - */ - function get_ip_address($convertToInteger = false) - { - return getIPAddress($convertToInteger); - } +if (!function_exists('get_ip_address')) { + /** + * Function get_ip_address + * + * @param bool $convertToInteger + * + * @return bool|int|string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 10/09/2020 59:22 + */ + function get_ip_address($convertToInteger = false) + { + return getIPAddress($convertToInteger); + } } -if ( ! function_exists('getUserIP')) { - /** - * Function getUserIP - * - * @param bool $convertToInteger - * - * @return bool|int|string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 10/09/2020 59:22 - */ - function getUserIP($convertToInteger = false) - { - return getIPAddress($convertToInteger); - } +if (!function_exists('getUserIP')) { + /** + * Function getUserIP + * + * @param bool $convertToInteger + * + * @return bool|int|string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 10/09/2020 59:22 + */ + function getUserIP($convertToInteger = false) + { + return getIPAddress($convertToInteger); + } } -if ( ! function_exists('validate_ip')) { - /** - * Function validate_ip - * - * @param $ip - * - * @return bool - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 10/02/2023 47:49 - */ - function validate_ip($ip) - { - return validateIP($ip); - } +if (!function_exists('validate_ip')) { + /** + * Function validate_ip + * + * @param $ip + * + * @return bool + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 10/02/2023 47:49 + */ + function validate_ip($ip) + { + return validateIP($ip); + } } -if ( ! function_exists('validateIP')) { - /** - * Function validateIP - * - * @param $ip - * - * @return bool - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 10/09/2020 59:32 - */ - function validateIP($ip) - { - return ! (filter_var($ip, FILTER_VALIDATE_IP) === false); - } +if (!function_exists('validateIP')) { + /** + * Function validateIP + * + * @param $ip + * + * @return bool + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 10/09/2020 59:32 + */ + function validateIP($ip) + { + return !(filter_var($ip, FILTER_VALIDATE_IP) === false); + } } -if ( ! function_exists('validateIPV4')) { - /** - * Function validateIPV4 - * - * @param $ip - * - * @return bool - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 10/09/2020 59:36 - */ - function validateIPV4($ip) - { - return ! (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false); - } +if (!function_exists('validateIPV4')) { + /** + * Function validateIPV4 + * + * @param $ip + * + * @return bool + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 10/09/2020 59:36 + */ + function validateIPV4($ip) + { + return !(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false); + } } -if ( ! function_exists('validateIPV6')) { - /** - * Function validateIPV6 - * - * @param $ip - * - * @return bool - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 10/09/2020 59:40 - */ - function validateIPV6($ip) - { - return ! (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === false); - } +if (!function_exists('validateIPV6')) { + /** + * Function validateIPV6 + * + * @param $ip + * + * @return bool + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 10/09/2020 59:40 + */ + function validateIPV6($ip) + { + return !(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === false); + } } -if ( ! function_exists('getIpInformation')) { - /** - * Function getIpInformation - * - * @param string $ip - * - * @return bool|string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 10/10/2020 00:31 - */ - function getIpInformation($ip = '') - { - $isIP = empty($ip) ? getIPAddress() : $ip; +if (!function_exists('getIpInformation')) { + /** + * Function getIpInformation + * + * @param string $ip + * + * @return bool|string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 10/10/2020 00:31 + */ + function getIpInformation($ip = '') + { + $isIP = empty($ip) ? getIPAddress() : $ip; - try { - $endpoint = 'http://ip-api.com/json/' . trim($isIP); - $curl = curl_init(); - curl_setopt_array($curl, array( - CURLOPT_URL => $endpoint, - CURLOPT_RETURNTRANSFER => true, - CURLOPT_ENCODING => "", - CURLOPT_MAXREDIRS => 10, - CURLOPT_TIMEOUT => 30, - CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, - CURLOPT_CUSTOMREQUEST => "GET", - CURLOPT_POSTFIELDS => "", - CURLOPT_HTTPHEADER => array(), - )); - $response = curl_exec($curl); - $err = curl_error($curl); - curl_close($curl); - if ($err) { - $response = "cURL Error #:" . $err; - } + try { + $endpoint = 'http://ip-api.com/json/' . trim($isIP); + $curl = curl_init(); + curl_setopt_array($curl, array( + CURLOPT_URL => $endpoint, + CURLOPT_RETURNTRANSFER => true, + CURLOPT_ENCODING => "", + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 30, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => "GET", + CURLOPT_POSTFIELDS => "", + CURLOPT_HTTPHEADER => array(), + )); + $response = curl_exec($curl); + $err = curl_error($curl); + curl_close($curl); + if ($err) { + $response = "cURL Error #:" . $err; + } - return $response; - } catch (Exception $e) { - if (function_exists('log_message')) { - log_message('error', __get_error_message__($e)); - log_message('error', __get_error_trace__($e)); - } + return $response; + } catch (Exception $e) { + if (function_exists('log_message')) { + log_message('error', __get_error_message__($e)); + log_message('error', __get_error_trace__($e)); + } - return $e->getMessage(); - } - } + return $e->getMessage(); + } + } } diff --git a/helpers/japan_helper.php b/helpers/japan_helper.php index 2a59311..29a0065 100644 --- a/helpers/japan_helper.php +++ b/helpers/japan_helper.php @@ -8,9 +8,9 @@ * Date: 18/04/2023 * Time: 10:44 */ -if ( ! function_exists('_japan_pref_code_')) { - function _japan_pref_code_() - { - return \nguyenanhung\CodeIgniter\BasicHelper\JapanUtils::getJapanPrefCode(); - } +if (!function_exists('_japan_pref_code_')) { + function _japan_pref_code_() + { + return \nguyenanhung\CodeIgniter\BasicHelper\JapanUtils::getJapanPrefCode(); + } } diff --git a/helpers/meta_helper.php b/helpers/meta_helper.php index e40e976..f7b6c30 100644 --- a/helpers/meta_helper.php +++ b/helpers/meta_helper.php @@ -8,33 +8,33 @@ * Date: 09/15/2021 * Time: 00:37 */ -if ( ! function_exists('setupMetaDnsPrefetch')) { - /** - * Function setupMetaDnsPrefetch - * - * @param string|array $dns - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 09/15/2021 44:45 - */ - function setupMetaDnsPrefetch($dns = '') - { - if (empty($dns)) { - return $dns; - } - if (is_array($dns)) { - $html = ''; - foreach ($dns as $domain) { - $domain = str_replace(array('https://', 'http://'), '', $domain); - $domain = trim($domain, '/'); - $html .= "" . PHP_EOL; - } - return $html; - } - $dns = str_replace(array('https://', 'http://'), '', $dns); - $dns = trim($dns, '/'); - return "" . PHP_EOL; - } +if (!function_exists('setupMetaDnsPrefetch')) { + /** + * Function setupMetaDnsPrefetch + * + * @param string|array $dns + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 09/15/2021 44:45 + */ + function setupMetaDnsPrefetch($dns = '') + { + if (empty($dns)) { + return $dns; + } + if (is_array($dns)) { + $html = ''; + foreach ($dns as $domain) { + $domain = str_replace(array('https://', 'http://'), '', $domain); + $domain = trim($domain, '/'); + $html .= "" . PHP_EOL; + } + return $html; + } + $dns = str_replace(array('https://', 'http://'), '', $dns); + $dns = trim($dns, '/'); + return "" . PHP_EOL; + } } diff --git a/helpers/money_helper.php b/helpers/money_helper.php index 869e06a..f2e219d 100644 --- a/helpers/money_helper.php +++ b/helpers/money_helper.php @@ -8,20 +8,20 @@ * Date: 15/02/2023 * Time: 00:40 */ -if ( ! function_exists('money_number_format')) { - function money_number_format($input, $showCents = true, $locale = null) - { - if (function_exists('numfmt_create') && function_exists('numfmt_format_currency') && function_exists( - 'locale_get_default' - )) { - setlocale(LC_MONETARY, $locale ?: locale_get_default()); - $numberOfDecimalPlaces = $showCents ? 2 : 0; - $formatter = numfmt_create('en_US', NumberFormatter::CURRENCY); - $formatter->setAttribute(NumberFormatter::FRACTION_DIGITS, $numberOfDecimalPlaces); +if (!function_exists('money_number_format')) { + function money_number_format($input, $showCents = true, $locale = null) + { + if (function_exists('numfmt_create') && function_exists('numfmt_format_currency') && function_exists( + 'locale_get_default' + )) { + setlocale(LC_MONETARY, $locale ?: locale_get_default()); + $numberOfDecimalPlaces = $showCents ? 2 : 0; + $formatter = numfmt_create('en_US', NumberFormatter::CURRENCY); + $formatter->setAttribute(NumberFormatter::FRACTION_DIGITS, $numberOfDecimalPlaces); - return numfmt_format_currency($formatter, $input, trim(localeconv()['int_curr_symbol'])); - } + return numfmt_format_currency($formatter, $input, trim(localeconv()['int_curr_symbol'])); + } - return $input; - } + return $input; + } } diff --git a/helpers/nanoid_helper.php b/helpers/nanoid_helper.php index 3e5b514..f555207 100644 --- a/helpers/nanoid_helper.php +++ b/helpers/nanoid_helper.php @@ -8,24 +8,24 @@ * Date: 09/14/2021 * Time: 13:06 */ -if ( ! function_exists('randomNanoId')) { - /** - * Function randomNanoId - * - * @param $size - * @param $prefix - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 20/03/2023 48:05 - */ - function randomNanoId($size = 21, $prefix = 'Bear-') - { - if (class_exists('Hidehalo\Nanoid\Client')) { - $client = new Hidehalo\Nanoid\Client(); - return $client->generateId($size); - } - return uniqid($prefix, true); - } +if (!function_exists('randomNanoId')) { + /** + * Function randomNanoId + * + * @param $size + * @param $prefix + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 20/03/2023 48:05 + */ + function randomNanoId($size = 21, $prefix = 'Bear-') + { + if (class_exists('Hidehalo\Nanoid\Client')) { + $client = new Hidehalo\Nanoid\Client(); + return $client->generateId($size); + } + return uniqid($prefix, true); + } } diff --git a/helpers/number_helper.php b/helpers/number_helper.php index a72eb04..a3be9fb 100644 --- a/helpers/number_helper.php +++ b/helpers/number_helper.php @@ -8,89 +8,89 @@ * Date: 18/01/2023 * Time: 00:36 */ -if ( ! function_exists('convertNumberToWords')) { - function convertNumberToWords($num) - { - $ones = array( - 0 => "", - 1 => "One", - 2 => "Two", - 3 => "Three", - 4 => "Four", - 5 => "Five", - 6 => "Six", - 7 => "Seven", - 8 => "Eight", - 9 => "Nine", - 10 => "Ten", - 11 => "Eleven", - 12 => "Twelve", - 13 => "Thirteen", - 14 => "Fourteen", - 15 => "Fifteen", - 16 => "Sixteen", - 17 => "Seventeen", - 18 => "Eighteen", - 19 => "Nineteen" - ); - $tens = array( - 0 => "", - 1 => "Ten", - 2 => "Twenty", - 3 => "Thirty", - 4 => "Forty", - 5 => "Fifty", - 6 => "Sixty", - 7 => "Seventy", - 8 => "Eighty", - 9 => "Ninety" - ); - $hundreds = array( - "Hundred", - "Thousand", - "Million", - "Billion", - "Trillion", - "Quadrillion" - ); - $num = number_format($num, 2, ".", ","); - $num_arr = explode(".", $num); - $wholenum = $num_arr[0]; - $decnum = $num_arr[1]; - $whole_arr = array_reverse(explode(",", $wholenum)); - krsort($whole_arr); - $returnTxt = ""; - foreach ($whole_arr as $key => $i) { - if ($i < 20) { - $returnTxt .= $ones[$i]; - } elseif ($i < 100) { - $returnTxt .= $tens[mb_substr($i, 0, 1)]; - $returnTxt .= " " . $ones[mb_substr($i, 1, 1)]; - } else { - $returnTxt .= $ones[mb_substr($i, 0, 1)] . " " . $hundreds[0]; - $returnTxt .= " " . $tens[mb_substr($i, 1, 1)]; - $returnTxt .= " " . $ones[mb_substr($i, 2, 1)]; - } - if ($key > 0) { - $returnTxt .= " " . $hundreds[$key] . " "; - } - } - if ($decnum > 0) { - $returnTxt .= " and "; - if ($decnum < 20) { - $returnTxt .= $ones[$decnum]; - } elseif ($decnum < 100) { - $returnTxt .= $tens[mb_substr($decnum, 0, 1)]; - $returnTxt .= " " . $ones[mb_substr($decnum, 1, 1)]; - } - } +if (!function_exists('convertNumberToWords')) { + function convertNumberToWords($num) + { + $ones = array( + 0 => "", + 1 => "One", + 2 => "Two", + 3 => "Three", + 4 => "Four", + 5 => "Five", + 6 => "Six", + 7 => "Seven", + 8 => "Eight", + 9 => "Nine", + 10 => "Ten", + 11 => "Eleven", + 12 => "Twelve", + 13 => "Thirteen", + 14 => "Fourteen", + 15 => "Fifteen", + 16 => "Sixteen", + 17 => "Seventeen", + 18 => "Eighteen", + 19 => "Nineteen" + ); + $tens = array( + 0 => "", + 1 => "Ten", + 2 => "Twenty", + 3 => "Thirty", + 4 => "Forty", + 5 => "Fifty", + 6 => "Sixty", + 7 => "Seventy", + 8 => "Eighty", + 9 => "Ninety" + ); + $hundreds = array( + "Hundred", + "Thousand", + "Million", + "Billion", + "Trillion", + "Quadrillion" + ); + $num = number_format($num, 2, ".", ","); + $num_arr = explode(".", $num); + $wholenum = $num_arr[0]; + $decnum = $num_arr[1]; + $whole_arr = array_reverse(explode(",", $wholenum)); + krsort($whole_arr); + $returnTxt = ""; + foreach ($whole_arr as $key => $i) { + if ($i < 20) { + $returnTxt .= $ones[$i]; + } elseif ($i < 100) { + $returnTxt .= $tens[mb_substr($i, 0, 1)]; + $returnTxt .= " " . $ones[mb_substr($i, 1, 1)]; + } else { + $returnTxt .= $ones[mb_substr($i, 0, 1)] . " " . $hundreds[0]; + $returnTxt .= " " . $tens[mb_substr($i, 1, 1)]; + $returnTxt .= " " . $ones[mb_substr($i, 2, 1)]; + } + if ($key > 0) { + $returnTxt .= " " . $hundreds[$key] . " "; + } + } + if ($decnum > 0) { + $returnTxt .= " and "; + if ($decnum < 20) { + $returnTxt .= $ones[$decnum]; + } elseif ($decnum < 100) { + $returnTxt .= $tens[mb_substr($decnum, 0, 1)]; + $returnTxt .= " " . $ones[mb_substr($decnum, 1, 1)]; + } + } - return $returnTxt; - } + return $returnTxt; + } } -if ( ! function_exists('convert_number_to_words')) { - function convert_number_to_words($num) - { - return convertNumberToWords($num); - } +if (!function_exists('convert_number_to_words')) { + function convert_number_to_words($num) + { + return convertNumberToWords($num); + } } diff --git a/helpers/paging_helper.php b/helpers/paging_helper.php index 9ac260c..8b93346 100644 --- a/helpers/paging_helper.php +++ b/helpers/paging_helper.php @@ -8,225 +8,225 @@ * Date: 09/11/2021 * Time: 09:22 */ -if ( ! function_exists('view_paginations')) { - /** - * Function view_paginations - * - * @param $page_type - * @param $total_item - * @param $item_per_page - * @param $current_page_number - * @param $page_link - * @param $begin - * @param $end - * @param $page_title - * @param $page_prefix - * @param $page_suffix - * - * @return string|null - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 14/02/2023 29:41 - */ - function view_paginations( - $page_type, - $total_item, - $item_per_page, - $current_page_number, - $page_link, - $begin, - $end, - $page_title = '', - $page_prefix = '/trang-', - $page_suffix = '.html' - ) { - if ($page_type === 'search_page' || $page_type === 'search') { - $page_prefix = '&page='; - $page_suffix = ''; - } - $data = array( - 'page_type' => $page_type, - 'page_link' => $page_link, - 'page_title' => $page_title, - 'page_prefix' => $page_prefix, - 'page_suffix' => $page_suffix, - 'current_page_number' => $current_page_number, - 'total_item' => $total_item, - 'item_per_page' => $item_per_page, - 'page_begin' => $begin, - 'page_end' => $end, - 'pre_rows' => 3, - 'suf_rows' => 3, - 'first_link' => ' ', - 'last_link' => ' ', - 'default_page_title' => 'trang', - 'default_last_page_name_title' => 'trang cuối', - 'left_class' => 'left', - 'right_class' => 'right', - 'selected_class' => 'selected' - ); - $pagination = new \nguyenanhung\Libraries\Pagination\Pagination\SimplePagination(); - $pagination->setData($data); - return $pagination->build(); - } +if (!function_exists('view_paginations')) { + /** + * Function view_paginations + * + * @param $page_type + * @param $total_item + * @param $item_per_page + * @param $current_page_number + * @param $page_link + * @param $begin + * @param $end + * @param $page_title + * @param $page_prefix + * @param $page_suffix + * + * @return string|null + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 14/02/2023 29:41 + */ + function view_paginations( + $page_type, + $total_item, + $item_per_page, + $current_page_number, + $page_link, + $begin, + $end, + $page_title = '', + $page_prefix = '/trang-', + $page_suffix = '.html' + ) { + if ($page_type === 'search_page' || $page_type === 'search') { + $page_prefix = '&page='; + $page_suffix = ''; + } + $data = array( + 'page_type' => $page_type, + 'page_link' => $page_link, + 'page_title' => $page_title, + 'page_prefix' => $page_prefix, + 'page_suffix' => $page_suffix, + 'current_page_number' => $current_page_number, + 'total_item' => $total_item, + 'item_per_page' => $item_per_page, + 'page_begin' => $begin, + 'page_end' => $end, + 'pre_rows' => 3, + 'suf_rows' => 3, + 'first_link' => ' ', + 'last_link' => ' ', + 'default_page_title' => 'trang', + 'default_last_page_name_title' => 'trang cuối', + 'left_class' => 'left', + 'right_class' => 'right', + 'selected_class' => 'selected' + ); + $pagination = new \nguyenanhung\Libraries\Pagination\Pagination\SimplePagination(); + $pagination->setData($data); + return $pagination->build(); + } } -if ( ! function_exists('view_more')) { - /** - * Function view_more - * - * @param $page_number - * @param $page_total - * @param $page_size - * @param $url - * @param $title - * @param $more_type - * @param $page_prefix - * @param $page_suffix - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 14/02/2023 28:06 - */ - function view_more( - $page_number, - $page_total, - $page_size, - $url = '', - $title = '', - $more_type = '', - $page_prefix = '/trang-', - $page_suffix = '.html' - ) { - if ($more_type === 'search_page' || $more_type === 'search') { - $page_prefix = '&page='; - $page_suffix = ''; - } - $data = array( - 'page_number' => $page_number, - 'total_item' => $page_total, - 'item_per_page' => $page_size, - 'page_link' => $url, - 'page_title' => $title, - 'page_type' => $more_type, - 'page_prefix' => $page_prefix, - 'page_suffix' => $page_suffix, - 'default_page_title' => 'trang', - 'default_page_title_more' => 'Xem thêm', - 'default_page_title_prev' => 'Trang trước' - ); - $pagination = new \nguyenanhung\Libraries\Pagination\Pagination\SimplePagination(); - $pagination->setData($data); - return $pagination->buildViewMore(); - } +if (!function_exists('view_more')) { + /** + * Function view_more + * + * @param $page_number + * @param $page_total + * @param $page_size + * @param $url + * @param $title + * @param $more_type + * @param $page_prefix + * @param $page_suffix + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 14/02/2023 28:06 + */ + function view_more( + $page_number, + $page_total, + $page_size, + $url = '', + $title = '', + $more_type = '', + $page_prefix = '/trang-', + $page_suffix = '.html' + ) { + if ($more_type === 'search_page' || $more_type === 'search') { + $page_prefix = '&page='; + $page_suffix = ''; + } + $data = array( + 'page_number' => $page_number, + 'total_item' => $page_total, + 'item_per_page' => $page_size, + 'page_link' => $url, + 'page_title' => $title, + 'page_type' => $more_type, + 'page_prefix' => $page_prefix, + 'page_suffix' => $page_suffix, + 'default_page_title' => 'trang', + 'default_page_title_more' => 'Xem thêm', + 'default_page_title_prev' => 'Trang trước' + ); + $pagination = new \nguyenanhung\Libraries\Pagination\Pagination\SimplePagination(); + $pagination->setData($data); + return $pagination->buildViewMore(); + } } -if ( ! function_exists('select_page')) { - /** - * Function select_page - * - * @param $total_rows - * @param $per_page - * @param $page_number - * @param $type - * @param $page_links - * @param $begin - * @param $end - * @param $title - * @param $page_prefix - * @param $page_suffix - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 14/02/2023 28:40 - */ - function select_page( - $total_rows, - $per_page, - $page_number, - $type = '', - $page_links = '', - $begin = '', - $end = '', - $title = '', - $page_prefix = '/trang-', - $page_suffix = '.html' - ) { - if ($type === 'search_page' || $type === 'search') { - $page_prefix = '&page='; - $page_suffix = ''; - } - $data = array( - 'page_number' => $page_number, - 'total_item' => $total_rows, - 'item_per_page' => $per_page, - 'page_link' => $page_links, - 'page_title' => $title, - 'page_type' => $type, - 'page_begin' => $begin, - 'page_end' => $end, - 'page_prefix' => $page_prefix, - 'page_suffix' => $page_suffix, - 'left_class' => 'left', - 'right_class' => 'right', - 'selected_class' => 'selected', - 'default_page_title' => 'trang', - 'default_last_page_name_title' => 'Trang cuối', - ); - $pagination = new \nguyenanhung\Libraries\Pagination\Pagination\SimplePagination(); - $pagination->setData($data); - return $pagination->buildSelectPage(); - } +if (!function_exists('select_page')) { + /** + * Function select_page + * + * @param $total_rows + * @param $per_page + * @param $page_number + * @param $type + * @param $page_links + * @param $begin + * @param $end + * @param $title + * @param $page_prefix + * @param $page_suffix + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 14/02/2023 28:40 + */ + function select_page( + $total_rows, + $per_page, + $page_number, + $type = '', + $page_links = '', + $begin = '', + $end = '', + $title = '', + $page_prefix = '/trang-', + $page_suffix = '.html' + ) { + if ($type === 'search_page' || $type === 'search') { + $page_prefix = '&page='; + $page_suffix = ''; + } + $data = array( + 'page_number' => $page_number, + 'total_item' => $total_rows, + 'item_per_page' => $per_page, + 'page_link' => $page_links, + 'page_title' => $title, + 'page_type' => $type, + 'page_begin' => $begin, + 'page_end' => $end, + 'page_prefix' => $page_prefix, + 'page_suffix' => $page_suffix, + 'left_class' => 'left', + 'right_class' => 'right', + 'selected_class' => 'selected', + 'default_page_title' => 'trang', + 'default_last_page_name_title' => 'Trang cuối', + ); + $pagination = new \nguyenanhung\Libraries\Pagination\Pagination\SimplePagination(); + $pagination->setData($data); + return $pagination->buildSelectPage(); + } } -if ( ! function_exists('get_paginations_title')) { - /** - * Function get_paginations_title - * - * @param $str - * - * @return array|string|string[] - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 14/02/2023 17:37 - */ - function get_paginations_title($str) - { - $pagination = new \nguyenanhung\Libraries\Pagination\Pagination\SimplePagination(); - return $pagination->getPaginationsTitle($str); - } +if (!function_exists('get_paginations_title')) { + /** + * Function get_paginations_title + * + * @param $str + * + * @return array|string|string[] + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 14/02/2023 17:37 + */ + function get_paginations_title($str) + { + $pagination = new \nguyenanhung\Libraries\Pagination\Pagination\SimplePagination(); + return $pagination->getPaginationsTitle($str); + } } -if ( ! function_exists('get_paginations_number')) { - /** - * Function get_paginations_number - * - * @param $str - * - * @return int - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 14/02/2023 16:17 - */ - function get_paginations_number($str) - { - $pagination = new \nguyenanhung\Libraries\Pagination\Pagination\SimplePagination(); - return $pagination->getPageNumber($str); - } +if (!function_exists('get_paginations_number')) { + /** + * Function get_paginations_number + * + * @param $str + * + * @return int + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 14/02/2023 16:17 + */ + function get_paginations_number($str) + { + $pagination = new \nguyenanhung\Libraries\Pagination\Pagination\SimplePagination(); + return $pagination->getPageNumber($str); + } } -if ( ! function_exists('bear_framework_news_view_pagination')) { - /** - * Function bear_framework_news_view_pagination - Hàm phân trang theo kiểu bear framework - * - * @param $data - * - * @return string|null - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 14/02/2023 16:29 - */ - function bear_framework_news_view_pagination($data = array()) - { - $pagination = new \nguyenanhung\Libraries\Pagination\Pagination\SimplePagination(); - $pagination->setData($data); - return $pagination->build(); - } +if (!function_exists('bear_framework_news_view_pagination')) { + /** + * Function bear_framework_news_view_pagination - Hàm phân trang theo kiểu bear framework + * + * @param $data + * + * @return string|null + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 14/02/2023 16:29 + */ + function bear_framework_news_view_pagination($data = array()) + { + $pagination = new \nguyenanhung\Libraries\Pagination\Pagination\SimplePagination(); + $pagination->setData($data); + return $pagination->build(); + } } diff --git a/helpers/placeholder_helper.php b/helpers/placeholder_helper.php index 5fc4d06..137b46b 100644 --- a/helpers/placeholder_helper.php +++ b/helpers/placeholder_helper.php @@ -8,38 +8,38 @@ * Date: 15/06/2022 * Time: 22:40 */ -if ( ! function_exists('placeholder_img')) { - /** - * Function placeholder_img - * - * @param $size - * @param $bg_color - * @param $text_color - * @param $text - * @param $domain - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 15/06/2022 42:35 - */ - function placeholder_img( - $size = '300x250', - $bg_color = '', - $text_color = '', - $text = '', - $domain = 'https://placehold.co/' - ) { - if ( ! empty($bg_color)) { - $bg_color = '/' . $bg_color; - } - if ( ! empty($text_color)) { - $text_color = '/' . $text_color; - } - if ( ! empty($text)) { - $text = '/' . $text; - } - $link = trim($domain) . trim($size) . trim($bg_color) . trim($text_color) . trim($text); - return 'Place-Holder'; - } +if (!function_exists('placeholder_img')) { + /** + * Function placeholder_img + * + * @param $size + * @param $bg_color + * @param $text_color + * @param $text + * @param $domain + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 15/06/2022 42:35 + */ + function placeholder_img( + $size = '300x250', + $bg_color = '', + $text_color = '', + $text = '', + $domain = 'https://placehold.co/' + ) { + if (!empty($bg_color)) { + $bg_color = '/' . $bg_color; + } + if (!empty($text_color)) { + $text_color = '/' . $text_color; + } + if (!empty($text)) { + $text = '/' . $text; + } + $link = trim($domain) . trim($size) . trim($bg_color) . trim($text_color) . trim($text); + return 'Place-Holder'; + } } diff --git a/helpers/request_helper.php b/helpers/request_helper.php index b6b115a..9aaed99 100644 --- a/helpers/request_helper.php +++ b/helpers/request_helper.php @@ -8,157 +8,157 @@ * Date: 10/05/2021 * Time: 03:52 */ -if ( ! function_exists('sendSimpleGetRequest')) { - /** - * Function sendSimpleGetRequest - * - * @param string $url URL Target Endpoint - * @param string|array|object $data Array Data to Request - * @param string $method GET or POST - * - * @return bool|string|null - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/03/2021 20:38 - */ - function sendSimpleGetRequest($url = '', $data = array(), $method = 'GET') - { - $method = mb_strtoupper($method); - if (( ! empty($data) && (is_array($data) || is_object($data)))) { - $target = $url . '?' . http_build_query($data); - } else { - $target = $url; - } - $parseUrl = parse_url($target); - $UA = 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.2 Safari/605.1.15'; - $curl = curl_init(); - $options = array( - CURLOPT_URL => $target, - CURLOPT_RETURNTRANSFER => true, - CURLOPT_ENCODING => "", - CURLOPT_MAXREDIRS => 10, - CURLOPT_TIMEOUT => 30, - CURLOPT_FOLLOWLOCATION => true, - CURLOPT_CUSTOMREQUEST => "GET", - CURLOPT_HTTPHEADER => array($UA), - ); - if (isset($parseUrl['scheme']) && $parseUrl['scheme'] === 'https') { - $options[CURLOPT_SSLVERSION] = CURL_SSLVERSION_TLSv1_2; - } - if (isset($parseUrl['scheme']) && $parseUrl['scheme'] === 'http') { - $options[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_1; - } - curl_setopt_array($curl, $options); - $response = curl_exec($curl); - $err = curl_error($curl); - curl_close($curl); - if ($err) { - $message = "cURL Error #: " . $err; - if (function_exists('log_message')) { - log_message('error', $message); - } +if (!function_exists('sendSimpleGetRequest')) { + /** + * Function sendSimpleGetRequest + * + * @param string $url URL Target Endpoint + * @param string|array|object $data Array Data to Request + * @param string $method GET or POST + * + * @return bool|string|null + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/03/2021 20:38 + */ + function sendSimpleGetRequest($url = '', $data = array(), $method = 'GET') + { + $method = mb_strtoupper($method); + if ((!empty($data) && (is_array($data) || is_object($data)))) { + $target = $url . '?' . http_build_query($data); + } else { + $target = $url; + } + $parseUrl = parse_url($target); + $UA = 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.2 Safari/605.1.15'; + $curl = curl_init(); + $options = array( + CURLOPT_URL => $target, + CURLOPT_RETURNTRANSFER => true, + CURLOPT_ENCODING => "", + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 30, + CURLOPT_FOLLOWLOCATION => true, + CURLOPT_CUSTOMREQUEST => "GET", + CURLOPT_HTTPHEADER => array($UA), + ); + if (isset($parseUrl['scheme']) && $parseUrl['scheme'] === 'https') { + $options[CURLOPT_SSLVERSION] = CURL_SSLVERSION_TLSv1_2; + } + if (isset($parseUrl['scheme']) && $parseUrl['scheme'] === 'http') { + $options[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_1; + } + curl_setopt_array($curl, $options); + $response = curl_exec($curl); + $err = curl_error($curl); + curl_close($curl); + if ($err) { + $message = "cURL Error #: " . $err; + if (function_exists('log_message')) { + log_message('error', $message); + } - return null; - } + return null; + } - return $response; - } + return $response; + } } -if ( ! function_exists('sendSimpleRestfulExecuteRequest')) { - function sendSimpleRestfulExecuteRequest($url, $type, $data = "", $header = null) - { - return \nguyenanhung\CodeIgniter\BasicHelper\SimpleRestful::execute($url, $type, $data, $header); - } +if (!function_exists('sendSimpleRestfulExecuteRequest')) { + function sendSimpleRestfulExecuteRequest($url, $type, $data = "", $header = null) + { + return \nguyenanhung\CodeIgniter\BasicHelper\SimpleRestful::execute($url, $type, $data, $header); + } } -if ( ! function_exists('bear_post_async_request')) { - /** - * Make an asynchronous POST request - * Thực hiện yêu cầu POST không đồng bộ trong nội bộ site mà không cần chờ phản hồi - * => Không ảnh hưởng, không trì hoãn tiến trình đang chạy - * - * @param mixed $url - * @param mixed $params - * @param array $headers - */ - function bear_post_async_request($url, $params, $headers = array()) - { - ksort($params); - $post_string = http_build_query($params); - $parts = parse_url($url); - $is_https = ($parts['scheme'] === 'https'); - $referer = $parts['scheme'] . '://' . $parts['host']; - if ( ! $is_https) { - $port = isset($parts['port']) ? $parts['port'] : 80; - $port = (int)$port; - $host = $parts['host'] . ($port !== 80 ? ':' . $port : ''); - isset($parts['port']) && $referer .= ':' . $parts['port']; - $fp = fsockopen($parts['host'], $port, $errno, $errorMessage, 30); - } else { - $options = array( - "ssl" => array( - "verify_peer" => false, - "verify_peer_name" => false - ) - ); - $context = stream_context_create($options); - $port = isset($parts['port']) ? $parts['port'] : 443; - $port = (int)$port; - $host = $parts['host'] . ($port !== 443 ? ':' . $port : ''); - $referer .= ':' . (isset($parts['port']) ? $parts['port'] : 443); - $fp = stream_socket_client( - 'ssl://' . $parts['host'] . ':' . $port, - $errno, - $errorMessage, - 30, - STREAM_CLIENT_CONNECT, - $context - ); - } - $path = isset($parts['path']) ? $parts['path'] : '/'; - if (isset($parts['query'])) { - $path .= '?' . $parts['query']; - } - $out = "POST " . $path . " HTTP/1.1\r\n"; - $out .= "Host: " . $host . "\r\n"; - $out .= "User-Agent: BEAR Framework\r\n"; - $out .= "Referer: " . $referer . "\r\n"; - $out .= "Content-Type: application/x-www-form-urlencoded\r\n"; - $out .= "Content-Length: " . mb_strlen($post_string) . "\r\n"; - if ( ! empty($headers)) { - foreach ($headers as $key => $value) { - $out .= $key . ": " . $value . "\r\n"; - } - } - $out .= "Connection: Close\r\n\r\n"; - $out .= $post_string; +if (!function_exists('bear_post_async_request')) { + /** + * Make an asynchronous POST request + * Thực hiện yêu cầu POST không đồng bộ trong nội bộ site mà không cần chờ phản hồi + * => Không ảnh hưởng, không trì hoãn tiến trình đang chạy + * + * @param mixed $url + * @param mixed $params + * @param array $headers + */ + function bear_post_async_request($url, $params, $headers = array()) + { + ksort($params); + $post_string = http_build_query($params); + $parts = parse_url($url); + $is_https = ($parts['scheme'] === 'https'); + $referer = $parts['scheme'] . '://' . $parts['host']; + if (!$is_https) { + $port = isset($parts['port']) ? $parts['port'] : 80; + $port = (int)$port; + $host = $parts['host'] . ($port !== 80 ? ':' . $port : ''); + isset($parts['port']) && $referer .= ':' . $parts['port']; + $fp = fsockopen($parts['host'], $port, $errno, $errorMessage, 30); + } else { + $options = array( + "ssl" => array( + "verify_peer" => false, + "verify_peer_name" => false + ) + ); + $context = stream_context_create($options); + $port = isset($parts['port']) ? $parts['port'] : 443; + $port = (int)$port; + $host = $parts['host'] . ($port !== 443 ? ':' . $port : ''); + $referer .= ':' . (isset($parts['port']) ? $parts['port'] : 443); + $fp = stream_socket_client( + 'ssl://' . $parts['host'] . ':' . $port, + $errno, + $errorMessage, + 30, + STREAM_CLIENT_CONNECT, + $context + ); + } + $path = isset($parts['path']) ? $parts['path'] : '/'; + if (isset($parts['query'])) { + $path .= '?' . $parts['query']; + } + $out = "POST " . $path . " HTTP/1.1\r\n"; + $out .= "Host: " . $host . "\r\n"; + $out .= "User-Agent: BEAR Framework\r\n"; + $out .= "Referer: " . $referer . "\r\n"; + $out .= "Content-Type: application/x-www-form-urlencoded\r\n"; + $out .= "Content-Length: " . mb_strlen($post_string) . "\r\n"; + if (!empty($headers)) { + foreach ($headers as $key => $value) { + $out .= $key . ": " . $value . "\r\n"; + } + } + $out .= "Connection: Close\r\n\r\n"; + $out .= $post_string; - fwrite($fp, $out); - if ($is_https) { - stream_set_timeout($fp, 1); - stream_get_contents($fp, -1); - } - fclose($fp); - } + fwrite($fp, $out); + if ($is_https) { + stream_set_timeout($fp, 1); + stream_get_contents($fp, -1); + } + fclose($fp); + } } -if ( ! function_exists('get_http_response_code')) { - /** - * Function get_http_response_code - * - * @param $url - * - * @return int|string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 07/08/2023 42:35 - */ - function get_http_response_code($url = '') - { - $uri = $url; - if ($uri !== '') { - $headers = get_headers($uri); - return mb_substr($headers[0], 9, 3); - } +if (!function_exists('get_http_response_code')) { + /** + * Function get_http_response_code + * + * @param $url + * + * @return int|string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 07/08/2023 42:35 + */ + function get_http_response_code($url = '') + { + $uri = $url; + if ($uri !== '') { + $headers = get_headers($uri); + return mb_substr($headers[0], 9, 3); + } - return 200; - } + return 200; + } } diff --git a/helpers/security_helper.php b/helpers/security_helper.php index 02e555f..252f925 100644 --- a/helpers/security_helper.php +++ b/helpers/security_helper.php @@ -8,161 +8,161 @@ * Date: 30/07/2022 * Time: 15:55 */ -if ( ! function_exists('xssValidation')) { - /** - * Function xssValidation - * - * @param $value - * - * @return bool - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 30/07/2022 57:32 - */ - function xssValidation($value) - { - $value = preg_replace('/%3A%2F%2F/', '', $value); // :// to empty - $value = preg_replace('/([\x00-\x08][\x0b-\x0c][\x0e-\x20])/', '', $value); - $value = preg_replace('/%u0([a-z0-9]{3})/i', '&#x\\1;', $value); - $value = preg_replace('/%([a-z0-9]{2})/i', '&#x\\1;', $value); - $value = str_ireplace( - array( - 'SCRIPT', - '&#x6A;&#x61;&#x76;&#x61;&#x73;&#x63;&#x72;&#x69;&#x70;&#x74;', - '/*', - '*/', - '', - '', - ' ', - ' ', - ' ', - '' - ), - '', - $value - ); +if (!function_exists('xssValidation')) { + /** + * Function xssValidation + * + * @param $value + * + * @return bool + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 30/07/2022 57:32 + */ + function xssValidation($value) + { + $value = preg_replace('/%3A%2F%2F/', '', $value); // :// to empty + $value = preg_replace('/([\x00-\x08][\x0b-\x0c][\x0e-\x20])/', '', $value); + $value = preg_replace('/%u0([a-z0-9]{3})/i', '&#x\\1;', $value); + $value = preg_replace('/%([a-z0-9]{2})/i', '&#x\\1;', $value); + $value = str_ireplace( + array( + 'SCRIPT', + '&#x6A;&#x61;&#x76;&#x61;&#x73;&#x63;&#x72;&#x69;&#x70;&#x74;', + '/*', + '*/', + '', + '', + ' ', + ' ', + ' ', + '' + ), + '', + $value + ); - $search = '/&#[xX]0{0,8}(21|22|23|24|25|26|27|28|29|2a|2b|2d|2f|30|31|32|33|34|35|36|37|38|39|3a|3b|3d|3f|40|41|42|43|44|45|46|47|48|49|4a|4b|4c|4d|4e|4f|50|51|52|53|54|55|56|57|58|59|5a|5b|5c|5d|5e|5f|60|61|62|63|64|65|66|67|68|69|6a|6b|6c|6d|6e|6f|70|71|72|73|74|75|76|77|78|79|7a|7b|7c|7d|7e);?/i'; - $value = preg_replace_callback($search, static function ($m) { - return mb_chr(hexdec($m[1])); - }, $value); + $search = '/&#[xX]0{0,8}(21|22|23|24|25|26|27|28|29|2a|2b|2d|2f|30|31|32|33|34|35|36|37|38|39|3a|3b|3d|3f|40|41|42|43|44|45|46|47|48|49|4a|4b|4c|4d|4e|4f|50|51|52|53|54|55|56|57|58|59|5a|5b|5c|5d|5e|5f|60|61|62|63|64|65|66|67|68|69|6a|6b|6c|6d|6e|6f|70|71|72|73|74|75|76|77|78|79|7a|7b|7c|7d|7e);?/i'; + $value = preg_replace_callback($search, static function ($m) { + return mb_chr(hexdec($m[1])); + }, $value); - $search = '/�{0,8}(33|34|35|36|37|38|39|40|41|42|43|45|47|48|49|50|51|52|53|54|55|56|57|58|59|61|63|64|65|66|67|68|69|70|71|72|73|74|75|76|77|78|79|80|81|82|83|84|85|86|87|88|89|90|91|92|93|94|95|96|97|98|99|100|101|102|103|104|105|106|107|108|109|110|111|112|113|114|115|116|117|118|119|120|121|122|123|124|125|126);?/i'; - $value = preg_replace_callback($search, static function ($m) { - return mb_chr($m[1]); - }, $value); + $search = '/�{0,8}(33|34|35|36|37|38|39|40|41|42|43|45|47|48|49|50|51|52|53|54|55|56|57|58|59|61|63|64|65|66|67|68|69|70|71|72|73|74|75|76|77|78|79|80|81|82|83|84|85|86|87|88|89|90|91|92|93|94|95|96|97|98|99|100|101|102|103|104|105|106|107|108|109|110|111|112|113|114|115|116|117|118|119|120|121|122|123|124|125|126);?/i'; + $value = preg_replace_callback($search, static function ($m) { + return mb_chr($m[1]); + }, $value); - $search = array( - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '<', - '\x3c', - '\x3C', - '\u003c', - '\u003C' - ); - $value = str_ireplace($search, '<', $value); + $search = array( + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '<', + '\x3c', + '\x3C', + '\u003c', + '\u003C' + ); + $value = str_ireplace($search, '<', $value); - $search = array( - 'expression' => '/e\s*x\s*p\s*r\s*e\s*s\s*s\s*i\s*o\s*n/si', - 'javascript' => '/j\s*a\s*v\s*a\s*s\s*c\s*r\s*i\s*p\s*t/si', - 'livescript' => '/l\s*i\s*v\s*e\s*s\s*c\s*r\s*i\s*p\s*t/si', - 'behavior' => '/b\s*e\s*h\s*a\s*v\s*i\s*o\s*r/si', - 'vbscript' => '/v\s*b\s*s\s*c\s*r\s*i\s*p\s*t/si', - 'script' => '/s\s*c\s*r\s*i\s*p\s*t/si', - 'applet' => '/a\s*p\s*p\s*l\s*e\s*t/si', - 'alert' => '/a\s*l\s*e\s*r\s*t/si', - 'document' => '/d\s*o\s*c\s*u\s*m\s*e\s*n\s*t/si', - 'write' => '/w\s*r\s*i\s*t\s*e/si', - 'cookie' => '/c\s*o\s*o\s*k\s*i\s*e/si', - 'window' => '/w\s*i\s*n\s*d\s*o\s*w/si', - 'data:' => '/d\s*a\s*t\s*a\s*\:/si' - ); - $value = preg_replace(array_values($search), array_keys($search), $value); - if (preg_match('/(expression|javascript|behavior|vbscript|mocha|livescript)(\:*)/', $value)) { - return false; - } + $search = array( + 'expression' => '/e\s*x\s*p\s*r\s*e\s*s\s*s\s*i\s*o\s*n/si', + 'javascript' => '/j\s*a\s*v\s*a\s*s\s*c\s*r\s*i\s*p\s*t/si', + 'livescript' => '/l\s*i\s*v\s*e\s*s\s*c\s*r\s*i\s*p\s*t/si', + 'behavior' => '/b\s*e\s*h\s*a\s*v\s*i\s*o\s*r/si', + 'vbscript' => '/v\s*b\s*s\s*c\s*r\s*i\s*p\s*t/si', + 'script' => '/s\s*c\s*r\s*i\s*p\s*t/si', + 'applet' => '/a\s*p\s*p\s*l\s*e\s*t/si', + 'alert' => '/a\s*l\s*e\s*r\s*t/si', + 'document' => '/d\s*o\s*c\s*u\s*m\s*e\s*n\s*t/si', + 'write' => '/w\s*r\s*i\s*t\s*e/si', + 'cookie' => '/c\s*o\s*o\s*k\s*i\s*e/si', + 'window' => '/w\s*i\s*n\s*d\s*o\s*w/si', + 'data:' => '/d\s*a\s*t\s*a\s*\:/si' + ); + $value = preg_replace(array_values($search), array_keys($search), $value); + if (preg_match('/(expression|javascript|behavior|vbscript|mocha|livescript)(\:*)/', $value)) { + return false; + } - if (strcasecmp($value, strip_tags($value)) !== 0) { - return false; - } + if (strcasecmp($value, strip_tags($value)) !== 0) { + return false; + } - $disableCommands = array( - 'base64_decode', - 'cmd', - 'passthru', - 'eval', - 'exec', - 'system', - 'fopen', - 'fsockopen', - 'file', - 'file_get_contents', - 'readfile', - 'unlink' - ); - if (preg_match('#(' . implode('|', $disableCommands) . ')(\s*)\((.*?)\)#si', $value)) { - return false; - } + $disableCommands = array( + 'base64_decode', + 'cmd', + 'passthru', + 'eval', + 'exec', + 'system', + 'fopen', + 'fsockopen', + 'file', + 'file_get_contents', + 'readfile', + 'unlink' + ); + if (preg_match('#(' . implode('|', $disableCommands) . ')(\s*)\((.*?)\)#si', $value)) { + return false; + } - return true; - } + return true; + } } diff --git a/helpers/sentry_helper.php b/helpers/sentry_helper.php index 0742233..efd2a9a 100644 --- a/helpers/sentry_helper.php +++ b/helpers/sentry_helper.php @@ -8,44 +8,44 @@ * Date: 08/01/2023 * Time: 23:34 */ -if ( ! function_exists('log_to_sentry')) { - /** - * Function log_to_sentry - * - * @param string $message - * @param array $context - * @param string $name - * - * @return bool|string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 07/27/2021 37:41 - */ - function log_to_sentry($message, $context, $name = 'hungng') - { - if ( ! function_exists('get_instance') || ! function_exists('config_item') || ! class_exists( - '\Sentry\ClientBuilder' - )) { - return false; - } - try { - $CI =& get_instance(); - $CI->load->config('config_sentry'); - // Init config sentry - $config = config_item('config_sentry'); - // Init logger use Monolog - $logger = new Monolog\Logger($name); - $client = Sentry\ClientBuilder::create(array('dsn' => $config['dsn']))->getClient(); - $handler = new Sentry\Monolog\Handler(new Sentry\State\Hub($client)); - $logger->pushHandler($handler); - $logger->error($message, $context); - return true; - } catch (Exception $e) { - $errorMsg = __get_error_message__($e); - if (function_exists('log_message')) { - log_message('error', $errorMsg); - } - return $errorMsg; - } - } +if (!function_exists('log_to_sentry')) { + /** + * Function log_to_sentry + * + * @param string $message + * @param array $context + * @param string $name + * + * @return bool|string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 07/27/2021 37:41 + */ + function log_to_sentry($message, $context, $name = 'hungng') + { + if (!function_exists('get_instance') || !function_exists('config_item') || !class_exists( + '\Sentry\ClientBuilder' + )) { + return false; + } + try { + $CI =& get_instance(); + $CI->load->config('config_sentry'); + // Init config sentry + $config = config_item('config_sentry'); + // Init logger use Monolog + $logger = new Monolog\Logger($name); + $client = Sentry\ClientBuilder::create(array('dsn' => $config['dsn']))->getClient(); + $handler = new Sentry\Monolog\Handler(new Sentry\State\Hub($client)); + $logger->pushHandler($handler); + $logger->error($message, $context); + return true; + } catch (Exception $e) { + $errorMsg = __get_error_message__($e); + if (function_exists('log_message')) { + log_message('error', $errorMsg); + } + return $errorMsg; + } + } } diff --git a/helpers/string_helper.php b/helpers/string_helper.php index 791f267..51356d1 100644 --- a/helpers/string_helper.php +++ b/helpers/string_helper.php @@ -8,629 +8,629 @@ * Date: 12/12/2022 * Time: 23:14 */ -if ( ! function_exists('countStringsInText')) { - /** - * Function countStringsInText - Hàm đếm số từ trong đoạn văn bản - * - * @param $str - * - * @return int - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 12/12/2022 19:18 - */ - function countStringsInText($str) - { - if (empty($str)) { - return 0; - } - $str = strip_tags($str); - $str = str_replace(PHP_EOL, '', $str); - $arr = explode(' ', $str); +if (!function_exists('countStringsInText')) { + /** + * Function countStringsInText - Hàm đếm số từ trong đoạn văn bản + * + * @param $str + * + * @return int + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 12/12/2022 19:18 + */ + function countStringsInText($str) + { + if (empty($str)) { + return 0; + } + $str = strip_tags($str); + $str = str_replace(PHP_EOL, '', $str); + $arr = explode(' ', $str); - return count($arr); - } + return count($arr); + } } -if ( ! function_exists('findMiddleInString')) { - /** - * Function findMiddleInString - Hàm lấy chuỗi ở giữa chuỗi bắt đầu và chuỗi kết thúc - * - * @param $str : toàn bộ chuỗi; - * @param $str_begin : chuỗi bắt đầu cuối cùng. - * @param $str_end : chuỗi kết thúc đầu tiên - * - * @return string: trả về chuỗi ở giữa chuỗi bắt đầu và chuỗi kết thúc, nếu không có thì trả về chính chuỗi đó.. - * - */ - function findMiddleInString($str, $str_begin, $str_end) - { - if (empty($str_begin)) { - $to = mb_strpos($str, $str_end); +if (!function_exists('findMiddleInString')) { + /** + * Function findMiddleInString - Hàm lấy chuỗi ở giữa chuỗi bắt đầu và chuỗi kết thúc + * + * @param $str : toàn bộ chuỗi; + * @param $str_begin : chuỗi bắt đầu cuối cùng. + * @param $str_end : chuỗi kết thúc đầu tiên + * + * @return string: trả về chuỗi ở giữa chuỗi bắt đầu và chuỗi kết thúc, nếu không có thì trả về chính chuỗi đó.. + * + */ + function findMiddleInString($str, $str_begin, $str_end) + { + if (empty($str_begin)) { + $to = mb_strpos($str, $str_end); - return trim(mb_substr($str, 0, $to)); - } - $from = mb_strrpos($str, $str_begin) + mb_strlen($str_begin) - 1; - if (empty($str_end)) { - return trim(mb_substr($str, $from + 1)); - } - $str = mb_substr($str, $from + 1); - $to = mb_strpos($str, $str_end); - $str = mb_substr($str, 0, $to); + return trim(mb_substr($str, 0, $to)); + } + $from = mb_strrpos($str, $str_begin) + mb_strlen($str_begin) - 1; + if (empty($str_end)) { + return trim(mb_substr($str, $from + 1)); + } + $str = mb_substr($str, $from + 1); + $to = mb_strpos($str, $str_end); + $str = mb_substr($str, 0, $to); - return trim($str); - } + return trim($str); + } } -if ( ! function_exists('str_insert')) { - /** - * Function str_insert - Inserts one or more strings into another string on a defined position. - * - * ### str_insert - * Related global function (description see above). - * - * > #### [( jump back )](#available-php-functions) - * - * ```php - * str_insert( array $keyValue, string $string ): string - * ``` - * - * #### Example - * ```php - * $keyValue = [ - * ':color' => 'brown', - * ':animal' => 'dog' - * ] - * $string = 'The quick :color fox jumps over the lazy :animal.'; - * - * str_insert( $keyValue, $string ); - * - * // The quick brown fox jumps over the lazy dog. - * ``` - * - * @param array $keyValue - * An associative array with key => value pairs. - * @param string $string - * The text with the strings to be replaced. - * - * @return string - * The replaced string. - */ - function str_insert($keyValue, $string) - { - if (arrayIsAssoc($keyValue)) { - foreach ($keyValue as $search => $replace) { - $string = str_replace($search, $replace, $string); - } - } +if (!function_exists('str_insert')) { + /** + * Function str_insert - Inserts one or more strings into another string on a defined position. + * + * ### str_insert + * Related global function (description see above). + * + * > #### [( jump back )](#available-php-functions) + * + * ```php + * str_insert( array $keyValue, string $string ): string + * ``` + * + * #### Example + * ```php + * $keyValue = [ + * ':color' => 'brown', + * ':animal' => 'dog' + * ] + * $string = 'The quick :color fox jumps over the lazy :animal.'; + * + * str_insert( $keyValue, $string ); + * + * // The quick brown fox jumps over the lazy dog. + * ``` + * + * @param array $keyValue + * An associative array with key => value pairs. + * @param string $string + * The text with the strings to be replaced. + * + * @return string + * The replaced string. + */ + function str_insert($keyValue, $string) + { + if (arrayIsAssoc($keyValue)) { + foreach ($keyValue as $search => $replace) { + $string = str_replace($search, $replace, $string); + } + } - return $string; - } + return $string; + } } -if ( ! function_exists('str_between')) { - /** - * Function str_between - Return the content in a string between a left and right element. - * - * ### str_between - * Related global function (description see above). - * - * > #### [( jump back )](#available-php-functions) - * - * ```php - * str_between( string $left, string $right, string $string ): array - * ``` - * - * #### Example - * ```php - * $string = 'foofoobarbar' - * - * str_between( '', '' $string ); - * - * // ( - * // [0] => foo - * // [1] => bar - * // ) - * ``` - * - * - * @param string $left - * The left element of the string to search. - * @param string $right - * The right element of the string to search. - * @param string $string - * The string to search in. - * - * @return array - * A result array with all matches of the search. - */ - function str_between($left, $right, $string) - { - preg_match_all('/' . preg_quote($left, '/') . '(.*?)' . preg_quote($right, '/') . '/s', $string, $matches); +if (!function_exists('str_between')) { + /** + * Function str_between - Return the content in a string between a left and right element. + * + * ### str_between + * Related global function (description see above). + * + * > #### [( jump back )](#available-php-functions) + * + * ```php + * str_between( string $left, string $right, string $string ): array + * ``` + * + * #### Example + * ```php + * $string = 'foofoobarbar' + * + * str_between( '', '' $string ); + * + * // ( + * // [0] => foo + * // [1] => bar + * // ) + * ``` + * + * + * @param string $left + * The left element of the string to search. + * @param string $right + * The right element of the string to search. + * @param string $string + * The string to search in. + * + * @return array + * A result array with all matches of the search. + */ + function str_between($left, $right, $string) + { + preg_match_all('/' . preg_quote($left, '/') . '(.*?)' . preg_quote($right, '/') . '/s', $string, $matches); - return array_map('trim', $matches[1]); - } + return array_map('trim', $matches[1]); + } } -if ( ! function_exists('str_after')) { - /** - * Function str_after - Return the part of a string after a given value. - * - * ### str_after - * Related global function (description see above). - * - * > #### [( jump back )](#available-php-functions) - * - * ```php - * str_after( string $search, string $string ): string - * ``` - * - * #### Example - * ```php - * $string = 'The quick brown fox jumps over the lazy dog'; - * - * str_after( 'fox' $string ); - * - * // jumps over the lazy dog - * ``` - * - * @param string $search - * The string to search for. - * @param string $string - * The string to search in. - * - * @return string - * The found string after the search string. Whitespaces at beginning will be removed. - */ - function str_after($search, $string) - { - return $search === '' ? $string : ltrim(array_reverse(explode($search, $string, 2))[0]); - } +if (!function_exists('str_after')) { + /** + * Function str_after - Return the part of a string after a given value. + * + * ### str_after + * Related global function (description see above). + * + * > #### [( jump back )](#available-php-functions) + * + * ```php + * str_after( string $search, string $string ): string + * ``` + * + * #### Example + * ```php + * $string = 'The quick brown fox jumps over the lazy dog'; + * + * str_after( 'fox' $string ); + * + * // jumps over the lazy dog + * ``` + * + * @param string $search + * The string to search for. + * @param string $string + * The string to search in. + * + * @return string + * The found string after the search string. Whitespaces at beginning will be removed. + */ + function str_after($search, $string) + { + return $search === '' ? $string : ltrim(array_reverse(explode($search, $string, 2))[0]); + } } -if ( ! function_exists('str_before')) { - /** - * Function str_before - Get the part of a string before a given value. - * - * ### str_before - * Related global function (description see above). - * - * > #### [( jump back )](#available-php-functions) - * - * ```php - * str_before( string $search, string $string ): string - * ``` - * - * #### Example - * ```php - * $string = 'The quick brown fox jumps over the lazy dog'; - * - * str_before( 'fox' $string ); - * - * // The quick brown - * ``` - * - * @param string $search - * The string to search for. - * @param string $string - * The string to search in. - * - * @return string - * The found string before the search string. Whitespaces at end will be removed. - */ - function str_before($search, $string) - { - return $search === '' ? $string : rtrim(explode($search, $string)[0]); - } +if (!function_exists('str_before')) { + /** + * Function str_before - Get the part of a string before a given value. + * + * ### str_before + * Related global function (description see above). + * + * > #### [( jump back )](#available-php-functions) + * + * ```php + * str_before( string $search, string $string ): string + * ``` + * + * #### Example + * ```php + * $string = 'The quick brown fox jumps over the lazy dog'; + * + * str_before( 'fox' $string ); + * + * // The quick brown + * ``` + * + * @param string $search + * The string to search for. + * @param string $string + * The string to search in. + * + * @return string + * The found string before the search string. Whitespaces at end will be removed. + */ + function str_before($search, $string) + { + return $search === '' ? $string : rtrim(explode($search, $string)[0]); + } } -if ( ! function_exists('str_limit_words')) { - /** - * Function str_limit_words - Limit the number of words in a string. Put value of $end to the string end. - * - * ### str_limit_words - * Related global function (description see above). - * - * > #### [( jump back )](#available-php-functions) - * - * ```php - * str_limit_words( string $string, int $limit = 10, string $end = '...' ): string - * ``` - * - * #### Example - * ```php - * $string = 'The quick brown fox jumps over the lazy dog'; - * - * str_limit_words( $string, 3 ); - * - * // The quick brown... - * ``` - * - * @param string $string - * The string to limit the words. - * @param int $limit - * The number of words to limit. Defaults to 10. - * @param string $end - * The string to end the cut string. Defaults to '...' - * - * @return string - * The limited string with $end at the end. - */ - function str_limit_words($string, $limit = 10, $end = '...') - { - $arrayWords = explode(' ', $string); +if (!function_exists('str_limit_words')) { + /** + * Function str_limit_words - Limit the number of words in a string. Put value of $end to the string end. + * + * ### str_limit_words + * Related global function (description see above). + * + * > #### [( jump back )](#available-php-functions) + * + * ```php + * str_limit_words( string $string, int $limit = 10, string $end = '...' ): string + * ``` + * + * #### Example + * ```php + * $string = 'The quick brown fox jumps over the lazy dog'; + * + * str_limit_words( $string, 3 ); + * + * // The quick brown... + * ``` + * + * @param string $string + * The string to limit the words. + * @param int $limit + * The number of words to limit. Defaults to 10. + * @param string $end + * The string to end the cut string. Defaults to '...' + * + * @return string + * The limited string with $end at the end. + */ + function str_limit_words($string, $limit = 10, $end = '...') + { + $arrayWords = explode(' ', $string); - if (count($arrayWords) <= $limit) { - return $string; - } + if (count($arrayWords) <= $limit) { + return $string; + } - return implode(' ', array_slice($arrayWords, 0, $limit)) . $end; - } + return implode(' ', array_slice($arrayWords, 0, $limit)) . $end; + } } -if ( ! function_exists('str_limit_characters')) { - /** - * Function str_limit_characters - Limit the number of characters in a string. Put value of $end to the string end. - * - * ### str_limit_characters - * Related global function (description see above). - * - * > #### [( jump back )](#available-php-functions) - * - * ```php - * str_limit_characters( string $string, int $limit = 100, string $end = '...' ): string - * ``` - * - * #### Example - * ```php - * $string = 'The quick brown fox jumps over the lazy dog'; - * - * str_limit_characters( $string, 15 ); - * - * // The quick brown... - * ``` - * - * @param string $string - * The string to limit the characters. - * @param int $limit - * The number of characters to limit. Defaults to 100. - * @param string $end - * The string to end the cut string. Defaults to '...' - * - * @return string - * The limited string with $end at the end. - */ - function str_limit_characters($string, $limit = 100, $end = '...') - { - if (mb_strwidth($string, 'UTF-8') <= $limit) { - return $string; - } +if (!function_exists('str_limit_characters')) { + /** + * Function str_limit_characters - Limit the number of characters in a string. Put value of $end to the string end. + * + * ### str_limit_characters + * Related global function (description see above). + * + * > #### [( jump back )](#available-php-functions) + * + * ```php + * str_limit_characters( string $string, int $limit = 100, string $end = '...' ): string + * ``` + * + * #### Example + * ```php + * $string = 'The quick brown fox jumps over the lazy dog'; + * + * str_limit_characters( $string, 15 ); + * + * // The quick brown... + * ``` + * + * @param string $string + * The string to limit the characters. + * @param int $limit + * The number of characters to limit. Defaults to 100. + * @param string $end + * The string to end the cut string. Defaults to '...' + * + * @return string + * The limited string with $end at the end. + */ + function str_limit_characters($string, $limit = 100, $end = '...') + { + if (mb_strwidth($string, 'UTF-8') <= $limit) { + return $string; + } - return rtrim(mb_strimwidth($string, 0, $limit, '', 'UTF-8')) . $end; - } + return rtrim(mb_strimwidth($string, 0, $limit, '', 'UTF-8')) . $end; + } } -if ( ! function_exists('str_contains')) { - /** - * Function str_contains - Tests if a string contains a given element - * - * ### str_contains - * Related global function (description see above). - * - * > #### [( jump back )](#available-php-functions) - * - * ```php - * str_contains( string|array $needle, string $haystack ): boolean - * ``` - * - * #### Example - * ```php - * $string = 'The quick brown fox jumps over the lazy dog'; - * $array = [ - * 'cat', - * 'fox' - * ]; - * - * str_contains( $array, $string ); - * - * // bool(true) - * ``` - * - * @param string|array $needle - * A string or an array of strings. - * @param string $haystack - * The string to search in. - * - * @return bool - * True if $needle is found, false otherwise. - */ - function str_contains($needle, $haystack) - { - foreach ((array)$needle as $ndl) { - if (mb_strpos($haystack, $ndl) !== false) { - return true; - } - } +if (!function_exists('str_contains')) { + /** + * Function str_contains - Tests if a string contains a given element + * + * ### str_contains + * Related global function (description see above). + * + * > #### [( jump back )](#available-php-functions) + * + * ```php + * str_contains( string|array $needle, string $haystack ): boolean + * ``` + * + * #### Example + * ```php + * $string = 'The quick brown fox jumps over the lazy dog'; + * $array = [ + * 'cat', + * 'fox' + * ]; + * + * str_contains( $array, $string ); + * + * // bool(true) + * ``` + * + * @param string|array $needle + * A string or an array of strings. + * @param string $haystack + * The string to search in. + * + * @return bool + * True if $needle is found, false otherwise. + */ + function str_contains($needle, $haystack) + { + foreach ((array)$needle as $ndl) { + if (mb_strpos($haystack, $ndl) !== false) { + return true; + } + } - return false; - } + return false; + } } -if ( ! function_exists('str_ignore_contains')) { - /** - * Function str_ignore_contains - Tests if a string contains a given element. Ignore case sensitivity. - * - * ### str_ignore_contains - * Related global function (description see above). - * - * > #### [( jump back )](#available-php-functions) - * - * ```php - * str_ignore_contains( string|array $needle, string $haystack ): boolean - * ``` - * - * #### Example - * ```php - * $string = 'The quick brown fox jumps over the lazy dog'; - * $array = [ - * 'Cat', - * 'Fox' - * ]; - * - * str_ignore_contains( $array, $string ); - * - * // bool(true) - * ``` - * - * @param string|array $needle - * A string or an array of strings. - * @param string $haystack - * The string to search in. - * - * @return bool - * True if $needle is found, false otherwise. - */ - function str_ignore_contains($needle, $haystack) - { - foreach ((array)$needle as $ndl) { - if (mb_stripos($haystack, $ndl) !== false) { - return true; - } - } +if (!function_exists('str_ignore_contains')) { + /** + * Function str_ignore_contains - Tests if a string contains a given element. Ignore case sensitivity. + * + * ### str_ignore_contains + * Related global function (description see above). + * + * > #### [( jump back )](#available-php-functions) + * + * ```php + * str_ignore_contains( string|array $needle, string $haystack ): boolean + * ``` + * + * #### Example + * ```php + * $string = 'The quick brown fox jumps over the lazy dog'; + * $array = [ + * 'Cat', + * 'Fox' + * ]; + * + * str_ignore_contains( $array, $string ); + * + * // bool(true) + * ``` + * + * @param string|array $needle + * A string or an array of strings. + * @param string $haystack + * The string to search in. + * + * @return bool + * True if $needle is found, false otherwise. + */ + function str_ignore_contains($needle, $haystack) + { + foreach ((array)$needle as $ndl) { + if (mb_stripos($haystack, $ndl) !== false) { + return true; + } + } - return false; - } + return false; + } } -if ( ! function_exists('str_starts_with')) { - /** - * Function str_starts_with - Determine if a given string starts with a given substring. - * - * ### str_starts_with - * Related global function (description see above). - * - * > #### [( jump back )](#available-php-functions) - * - * ```php - * str_starts_with( string|array $needle, string $haystack ): boolean - * ``` - * - * #### Example - * ```php - * $string = 'The quick brown fox jumps over the lazy dog'; - * $array = [ - * 'Cat', - * 'The' - * ]; - * - * str_starts_with( $array, $string ); - * - * // bool(true) - * ``` - * - * @param string|array $needle - * The string or array of strings to search for. - * @param string $haystack - * The string to search in. - * - * @return bool - * True if $needle was found, false otherwise. - */ - function str_starts_with($needle, $haystack) - { - foreach ((array)$needle as $ndl) { - if ($ndl !== '' && mb_strpos($haystack, (string)$ndl) === 0) { - return true; - } - } +if (!function_exists('str_starts_with')) { + /** + * Function str_starts_with - Determine if a given string starts with a given substring. + * + * ### str_starts_with + * Related global function (description see above). + * + * > #### [( jump back )](#available-php-functions) + * + * ```php + * str_starts_with( string|array $needle, string $haystack ): boolean + * ``` + * + * #### Example + * ```php + * $string = 'The quick brown fox jumps over the lazy dog'; + * $array = [ + * 'Cat', + * 'The' + * ]; + * + * str_starts_with( $array, $string ); + * + * // bool(true) + * ``` + * + * @param string|array $needle + * The string or array of strings to search for. + * @param string $haystack + * The string to search in. + * + * @return bool + * True if $needle was found, false otherwise. + */ + function str_starts_with($needle, $haystack) + { + foreach ((array)$needle as $ndl) { + if ($ndl !== '' && mb_strpos($haystack, (string)$ndl) === 0) { + return true; + } + } - return false; - } + return false; + } } -if ( ! function_exists('str_ignore_starts_with')) { - /** - * Function str_ignore_starts_with - Determine if a given string starts with a given substring. Ignore case sensitivity. - * - * ### str_ignore_starts_with - * Related global function (description see above). - * - * > #### [( jump back )](#available-php-functions) - * - * ```php - * str_ignore_starts_with( string|array $needle, string $haystack ): boolean - * ``` - * - * #### Example - * ```php - * $string = 'The quick brown fox jumps over the lazy dog'; - * $array = [ - * 'cat', - * 'the' - * ]; - * - * str_ignore_starts_with( $array, $string ); - * - * // bool(true) - * ``` - * - * @param string|array $needle - * The string or array of strings to search for. - * @param string $haystack - * The string to search in. - * - * @return bool - * True if $needle was found, false otherwise. - */ - function str_ignore_starts_with($needle, $haystack) - { - $hs = mb_strtolower($haystack); +if (!function_exists('str_ignore_starts_with')) { + /** + * Function str_ignore_starts_with - Determine if a given string starts with a given substring. Ignore case sensitivity. + * + * ### str_ignore_starts_with + * Related global function (description see above). + * + * > #### [( jump back )](#available-php-functions) + * + * ```php + * str_ignore_starts_with( string|array $needle, string $haystack ): boolean + * ``` + * + * #### Example + * ```php + * $string = 'The quick brown fox jumps over the lazy dog'; + * $array = [ + * 'cat', + * 'the' + * ]; + * + * str_ignore_starts_with( $array, $string ); + * + * // bool(true) + * ``` + * + * @param string|array $needle + * The string or array of strings to search for. + * @param string $haystack + * The string to search in. + * + * @return bool + * True if $needle was found, false otherwise. + */ + function str_ignore_starts_with($needle, $haystack) + { + $hs = mb_strtolower($haystack); - foreach ((array)$needle as $ndl) { - $n = mb_strtolower($ndl); - if ($n !== '' && mb_strpos($hs, $n) === 0) { - return true; - } - } + foreach ((array)$needle as $ndl) { + $n = mb_strtolower($ndl); + if ($n !== '' && mb_strpos($hs, $n) === 0) { + return true; + } + } - return false; - } + return false; + } } -if ( ! function_exists('str_ends_with')) { - /** - * Function str_ends_with - Determine if a given string ends with a given substring. - * - * ### str_ends_with - * Related global function (description see above). - * - * > #### [( jump back )](#available-php-functions) - * - * ```php - * str_ends_with( string|array $needle, string $haystack ): boolean - * ``` - * - * #### Example - * ```php - * $string = 'The quick brown fox jumps over the lazy dog'; - * $array = [ - * 'cat', - * 'dog' - * ]; - * - * str_ends_with( $array, $string ); - * - * // bool(true) - * ``` - * - * @param string|array $needle - * The string or array of strings to search for. - * - * @param string $haystack - * The string to search in. - * - * @return bool - * True if $needle was found, false otherwise. - */ - function str_ends_with($needle, $haystack) - { - foreach ((array)$needle as $ndl) { - $length = mb_strlen($ndl); - if ($length === 0 || (mb_substr($haystack, -$length) === (string)$ndl)) { - return true; - } - } +if (!function_exists('str_ends_with')) { + /** + * Function str_ends_with - Determine if a given string ends with a given substring. + * + * ### str_ends_with + * Related global function (description see above). + * + * > #### [( jump back )](#available-php-functions) + * + * ```php + * str_ends_with( string|array $needle, string $haystack ): boolean + * ``` + * + * #### Example + * ```php + * $string = 'The quick brown fox jumps over the lazy dog'; + * $array = [ + * 'cat', + * 'dog' + * ]; + * + * str_ends_with( $array, $string ); + * + * // bool(true) + * ``` + * + * @param string|array $needle + * The string or array of strings to search for. + * + * @param string $haystack + * The string to search in. + * + * @return bool + * True if $needle was found, false otherwise. + */ + function str_ends_with($needle, $haystack) + { + foreach ((array)$needle as $ndl) { + $length = mb_strlen($ndl); + if ($length === 0 || (mb_substr($haystack, -$length) === (string)$ndl)) { + return true; + } + } - return false; - } + return false; + } } -if ( ! function_exists('str_ignore_ends_with')) { - /** - * Function str_ignore_ends_with - Determine if a given string ends with a given substring. - * - * ### str_ignore_ends_with - * Related global function (description see above). - * - * > #### [( jump back )](#available-php-functions) - * - * ```php - * str_ignore_ends_with( string|array $needle, string $haystack ): boolean - * ``` - * - * #### Example - * ```php - * $string = 'The quick brown fox jumps over the lazy dog'; - * $array = [ - * 'Cat', - * 'Dog' - * ]; - * - * str_ignore_ends_with( $array, $string ); - * - * // bool(true) - * ``` - * - * @param string|array $needle - * The string or array of strings to search for. - * @param string $haystack - * The string to search in. - * - * @return bool - * True if $needle was found, false otherwise. - */ - function str_ignore_ends_with($needle, $haystack) - { - $hs = mb_strtolower($haystack); +if (!function_exists('str_ignore_ends_with')) { + /** + * Function str_ignore_ends_with - Determine if a given string ends with a given substring. + * + * ### str_ignore_ends_with + * Related global function (description see above). + * + * > #### [( jump back )](#available-php-functions) + * + * ```php + * str_ignore_ends_with( string|array $needle, string $haystack ): boolean + * ``` + * + * #### Example + * ```php + * $string = 'The quick brown fox jumps over the lazy dog'; + * $array = [ + * 'Cat', + * 'Dog' + * ]; + * + * str_ignore_ends_with( $array, $string ); + * + * // bool(true) + * ``` + * + * @param string|array $needle + * The string or array of strings to search for. + * @param string $haystack + * The string to search in. + * + * @return bool + * True if $needle was found, false otherwise. + */ + function str_ignore_ends_with($needle, $haystack) + { + $hs = mb_strtolower($haystack); - foreach ((array)$needle as $ndl) { - $n = mb_strtolower($ndl); - $length = mb_strlen($ndl); - if ($length === 0 || (mb_substr($hs, -$length) === $n)) { - return true; - } - } + foreach ((array)$needle as $ndl) { + $n = mb_strtolower($ndl); + $length = mb_strlen($ndl); + if ($length === 0 || (mb_substr($hs, -$length) === $n)) { + return true; + } + } - return false; - } + return false; + } } -if ( ! function_exists('str_after_last')) { - /** - * Function str_after_last - Return the part of a string after the last occurrence of a given search value. - * - * ### str_after_last - * Related global function (description see above). - * - * > #### [( jump back )](#available-php-functions) - * - * ```php - * str_after_last( string $search, string $string ): string - * ``` - * - * #### Example - * ```php - * $path = "/var/www/html/public/img/image.jpg"; - * - * str_after_last( '/' $path ); - * - * // image.jpg - * ``` - * - * @param string $search - * The string to search for. - * @param string $string - * The string to search in. - * - * @return string - * The found string after the last occurrence of the search string. Whitespaces at beginning will be removed. - */ - function str_after_last($search, $string) - { - return $search === '' ? $string : ltrim(array_reverse(explode($search, $string))[0]); - } +if (!function_exists('str_after_last')) { + /** + * Function str_after_last - Return the part of a string after the last occurrence of a given search value. + * + * ### str_after_last + * Related global function (description see above). + * + * > #### [( jump back )](#available-php-functions) + * + * ```php + * str_after_last( string $search, string $string ): string + * ``` + * + * #### Example + * ```php + * $path = "/var/www/html/public/img/image.jpg"; + * + * str_after_last( '/' $path ); + * + * // image.jpg + * ``` + * + * @param string $search + * The string to search for. + * @param string $string + * The string to search in. + * + * @return string + * The found string after the last occurrence of the search string. Whitespaces at beginning will be removed. + */ + function str_after_last($search, $string) + { + return $search === '' ? $string : ltrim(array_reverse(explode($search, $string))[0]); + } } -if ( ! function_exists('hide_characters')) { - function hide_characters($text) - { - $string_array = str_split($text); +if (!function_exists('hide_characters')) { + function hide_characters($text) + { + $string_array = str_split($text); - $return_text = ""; + $return_text = ""; - for ($i = 0, $iMax = mb_strlen($text); $i < $iMax; $i++) { - if ($i % 3 === 2) { - $return_text .= 'x'; - } else { - $return_text .= $string_array[$i]; - } - } + for ($i = 0, $iMax = mb_strlen($text); $i < $iMax; $i++) { + if ($i % 3 === 2) { + $return_text .= 'x'; + } else { + $return_text .= $string_array[$i]; + } + } - return $return_text; - } + return $return_text; + } } diff --git a/helpers/text_helper.php b/helpers/text_helper.php index a2c82f5..774ea9b 100644 --- a/helpers/text_helper.php +++ b/helpers/text_helper.php @@ -8,853 +8,853 @@ * Date: 09/11/2021 * Time: 09:01 */ -if ( ! function_exists('convert_string_utf8_to_vietnamese')) { - /** - * Function convert_string_utf8_to_vietnamese - * - * @param $str - * - * @return array|string|string[] - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 16/02/2023 58:33 - */ - function convert_string_utf8_to_vietnamese($str = '') - { - if (empty($str)) { - return $str; - } - $str = trim($str); - if ($str !== '') { - $str = str_replace( - array( - 'Á', - 'á', - 'Â', - 'â', - '´', - 'Æ', - 'æ', - 'À', - 'à', - 'ℵ', - 'Α', - 'α', - '&', - '∧', - '∠', - 'Å', - 'å', - '≈', - 'Ã', - 'ã', - 'Ä', - 'ä', - '„', - 'Β', - 'β', - '¦', - '•', - '∩', - 'Ç', - 'ç', - '¸', - '¢', - 'Χ', - 'χ', - 'ˆ', - '♣', - '≅', - '©', - '↵', - '∪', - '¤', - '†', - '‡', - '↓', - '⇓', - '°', - 'Δ', - 'δ', - '♦', - '÷', - 'É', - 'é', - 'Ê', - 'ê', - 'È', - 'è', - '∅', - ' ', - ' ', - 'Ε', - 'ε', - '≡', - 'Η', - 'η', - 'Ð', - 'ð', - 'Ë', - 'ë', - '€', - '∃', - 'ƒ', - '∀', - '½', - '¼', - '¾', - '⁄', - 'Γ', - 'γ', - '≥', - '↔', - '⇔', - '♥', - '…', - 'Í', - 'í', - 'Î', - 'î', - '¡', - 'Ì', - 'ì', - 'ℑ', - '∞', - '∫', - 'Ι', - 'ι', - '¿', - '∈', - 'Ï', - 'ï', - 'Κ', - 'κ', - 'Λ', - 'λ', - '⟨', - '«', - '←', - '⇐', - '⌈', - '“', - '≤', - '⌊', - '∗', - '◊', - '‎', - '‹', - '‘', - '¯', - '—', - 'µ', - '·', - '−', - 'Μ', - 'μ', - '∇', - ' ', - '–', - '≠', - '∋', - '¬', - '∉', - '⊄', - 'Ñ', - 'ñ', - 'Ν', - 'ν', - 'Ó', - 'ó', - 'Ô', - 'ô', - 'Œ', - 'œ', - 'Ò', - 'ò', - '‾', - 'Ω', - 'ω', - 'Ο', - 'ο', - '⊕', - '∨', - 'ª', - 'º', - 'Ø', - 'ø', - 'Õ', - 'õ', - '⊗', - 'Ö', - 'ö', - '¶', - '∂', - '‰', - '⊥', - 'Φ', - 'φ', - 'Π', - 'π', - 'ϖ', - '±', - '£', - '′', - '″', - '∏', - '∝', - 'Ψ', - 'ψ', - '√', - '⟩', - '»', - '→', - '⇒', - '⌉', - '”', - 'ℜ', - '®', - '⌋', - 'Ρ', - 'ρ', - '‏', - '›', - '’', - '‚', - 'Š', - 'š', - '⋅', - '§', - '­', - 'Σ', - 'σ', - 'ς', - '∼', - '♠', - '⊂', - '⊆', - '∑', - '¹', - '²', - '³', - '⊃', - '⊇', - 'ß', - 'Τ', - 'τ', - '∴', - 'Θ', - 'θ', - 'ϑ', - ' ', - 'Þ', - 'þ', - '˜', - '×', - '™', - 'Ú', - 'ú', - '↑', - '⇑', - 'Û', - 'û', - 'Ù', - 'ù', - '¨', - 'ϒ', - 'Υ', - 'υ', - 'Ü', - 'ü', - '℘', - 'Ξ', - 'ξ', - 'Ý', - 'ý', - '¥', - 'ÿ', - 'Ÿ', - 'Ζ', - 'ζ', - '‍', - '‌', - '>', - '<', - '"' - ), - array( - 'Á', - 'á', - 'Â', - 'â', - '´', - 'Æ', - 'æ', - 'À', - 'à', - 'ℵ', - 'Α', - 'α', - '&', - '∧', - '∠', - 'Å', - 'å', - '≈', - 'Ã', - 'ã', - 'Ä', - 'ä', - '„', - 'Β', - 'β', - '¦', - '•', - '∩', - 'Ç', - 'ç', - '¸', - '¢', - 'Χ', - 'χ', - 'ˆ', - '♣', - '≅', - '©', - '↵', - '∪', - '¤', - '†', - '‡', - '↓', - '⇓', - '°', - 'Δ', - 'δ', - '♦', - '÷', - 'É', - 'é', - 'Ê', - 'ê', - 'È', - 'è', - '∅', - ' ', - ' ', - 'Ε', - 'ε', - '≡', - 'Η', - 'η', - 'Ð', - 'ð', - 'Ë', - 'ë', - '€', - '∃', - 'ƒ', - '∀', - '½', - '¼', - '¾', - '⁄', - 'Γ', - 'γ', - '≥', - '↔', - '⇔', - '♥', - '…', - 'Í', - 'í', - 'Î', - 'î', - '¡', - 'Ì', - 'ì', - 'ℑ', - '∞', - '∫', - 'Ι', - 'ι', - '¿', - '∈', - 'Ï', - 'ï', - 'Κ', - 'κ', - 'Λ', - 'λ', - '〈', - '«', - '←', - '⇐', - '⌈', - '“', - '≤', - '⌊', - '∗', - '◊', - '‎', - '‹', - '‘', - '¯', - '—', - 'µ', - '·', - '−', - 'Μ', - 'μ', - '∇', - ' ', - '–', - '≠', - '∋', - '¬', - '∉', - '⊄', - 'Ñ', - 'ñ', - 'Ν', - 'ν', - 'Ó', - 'ó', - 'Ô', - 'ô', - 'Œ', - 'œ', - 'Ò', - 'ò', - '‾', - 'Ω', - 'ω', - 'Ο', - 'ο', - '⊕', - '∨', - 'ª', - 'º', - 'Ø', - 'ø', - 'Õ', - 'õ', - '⊗', - 'Ö', - 'ö', - '¶', - '∂', - '‰', - '⊥', - 'Φ', - 'φ', - 'Π', - 'π', - 'ϖ', - '±', - '£', - '′', - '″', - '∏', - '∝', - 'Ψ', - 'ψ', - '√', - '〉', - '»', - '→', - '⇒', - '⌉', - '”', - 'ℜ', - '®', - '⌋', - 'Ρ', - 'ρ', - '‏', - '›', - '’', - '‚', - 'Š', - 'š', - '⋅', - '§', - '­', - 'Σ', - 'σ', - 'ς', - '∼', - '♠', - '⊂', - '⊆', - '∑', - '¹', - '²', - '³', - '⊃', - '⊇', - 'ß', - 'Τ', - 'τ', - '∴', - 'Θ', - 'θ', - 'ϑ', - ' ', - 'Þ', - 'þ', - '˜', - '×', - '™', - 'Ú', - 'ú', - '↑', - '⇑', - 'Û', - 'û', - 'Ù', - 'ù', - '¨', - 'ϒ', - 'Υ', - 'υ', - 'Ü', - 'ü', - '℘', - 'Ξ', - 'ξ', - 'Ý', - 'ý', - '¥', - 'ÿ', - 'Ÿ', - 'Ζ', - 'ζ', - '‍', - '‌', - '>', - '<', - '"' - ), - $str - ); - } +if (!function_exists('convert_string_utf8_to_vietnamese')) { + /** + * Function convert_string_utf8_to_vietnamese + * + * @param $str + * + * @return array|string|string[] + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 16/02/2023 58:33 + */ + function convert_string_utf8_to_vietnamese($str = '') + { + if (empty($str)) { + return $str; + } + $str = trim($str); + if ($str !== '') { + $str = str_replace( + array( + 'Á', + 'á', + 'Â', + 'â', + '´', + 'Æ', + 'æ', + 'À', + 'à', + 'ℵ', + 'Α', + 'α', + '&', + '∧', + '∠', + 'Å', + 'å', + '≈', + 'Ã', + 'ã', + 'Ä', + 'ä', + '„', + 'Β', + 'β', + '¦', + '•', + '∩', + 'Ç', + 'ç', + '¸', + '¢', + 'Χ', + 'χ', + 'ˆ', + '♣', + '≅', + '©', + '↵', + '∪', + '¤', + '†', + '‡', + '↓', + '⇓', + '°', + 'Δ', + 'δ', + '♦', + '÷', + 'É', + 'é', + 'Ê', + 'ê', + 'È', + 'è', + '∅', + ' ', + ' ', + 'Ε', + 'ε', + '≡', + 'Η', + 'η', + 'Ð', + 'ð', + 'Ë', + 'ë', + '€', + '∃', + 'ƒ', + '∀', + '½', + '¼', + '¾', + '⁄', + 'Γ', + 'γ', + '≥', + '↔', + '⇔', + '♥', + '…', + 'Í', + 'í', + 'Î', + 'î', + '¡', + 'Ì', + 'ì', + 'ℑ', + '∞', + '∫', + 'Ι', + 'ι', + '¿', + '∈', + 'Ï', + 'ï', + 'Κ', + 'κ', + 'Λ', + 'λ', + '⟨', + '«', + '←', + '⇐', + '⌈', + '“', + '≤', + '⌊', + '∗', + '◊', + '‎', + '‹', + '‘', + '¯', + '—', + 'µ', + '·', + '−', + 'Μ', + 'μ', + '∇', + ' ', + '–', + '≠', + '∋', + '¬', + '∉', + '⊄', + 'Ñ', + 'ñ', + 'Ν', + 'ν', + 'Ó', + 'ó', + 'Ô', + 'ô', + 'Œ', + 'œ', + 'Ò', + 'ò', + '‾', + 'Ω', + 'ω', + 'Ο', + 'ο', + '⊕', + '∨', + 'ª', + 'º', + 'Ø', + 'ø', + 'Õ', + 'õ', + '⊗', + 'Ö', + 'ö', + '¶', + '∂', + '‰', + '⊥', + 'Φ', + 'φ', + 'Π', + 'π', + 'ϖ', + '±', + '£', + '′', + '″', + '∏', + '∝', + 'Ψ', + 'ψ', + '√', + '⟩', + '»', + '→', + '⇒', + '⌉', + '”', + 'ℜ', + '®', + '⌋', + 'Ρ', + 'ρ', + '‏', + '›', + '’', + '‚', + 'Š', + 'š', + '⋅', + '§', + '­', + 'Σ', + 'σ', + 'ς', + '∼', + '♠', + '⊂', + '⊆', + '∑', + '¹', + '²', + '³', + '⊃', + '⊇', + 'ß', + 'Τ', + 'τ', + '∴', + 'Θ', + 'θ', + 'ϑ', + ' ', + 'Þ', + 'þ', + '˜', + '×', + '™', + 'Ú', + 'ú', + '↑', + '⇑', + 'Û', + 'û', + 'Ù', + 'ù', + '¨', + 'ϒ', + 'Υ', + 'υ', + 'Ü', + 'ü', + '℘', + 'Ξ', + 'ξ', + 'Ý', + 'ý', + '¥', + 'ÿ', + 'Ÿ', + 'Ζ', + 'ζ', + '‍', + '‌', + '>', + '<', + '"' + ), + array( + 'Á', + 'á', + 'Â', + 'â', + '´', + 'Æ', + 'æ', + 'À', + 'à', + 'ℵ', + 'Α', + 'α', + '&', + '∧', + '∠', + 'Å', + 'å', + '≈', + 'Ã', + 'ã', + 'Ä', + 'ä', + '„', + 'Β', + 'β', + '¦', + '•', + '∩', + 'Ç', + 'ç', + '¸', + '¢', + 'Χ', + 'χ', + 'ˆ', + '♣', + '≅', + '©', + '↵', + '∪', + '¤', + '†', + '‡', + '↓', + '⇓', + '°', + 'Δ', + 'δ', + '♦', + '÷', + 'É', + 'é', + 'Ê', + 'ê', + 'È', + 'è', + '∅', + ' ', + ' ', + 'Ε', + 'ε', + '≡', + 'Η', + 'η', + 'Ð', + 'ð', + 'Ë', + 'ë', + '€', + '∃', + 'ƒ', + '∀', + '½', + '¼', + '¾', + '⁄', + 'Γ', + 'γ', + '≥', + '↔', + '⇔', + '♥', + '…', + 'Í', + 'í', + 'Î', + 'î', + '¡', + 'Ì', + 'ì', + 'ℑ', + '∞', + '∫', + 'Ι', + 'ι', + '¿', + '∈', + 'Ï', + 'ï', + 'Κ', + 'κ', + 'Λ', + 'λ', + '〈', + '«', + '←', + '⇐', + '⌈', + '“', + '≤', + '⌊', + '∗', + '◊', + '‎', + '‹', + '‘', + '¯', + '—', + 'µ', + '·', + '−', + 'Μ', + 'μ', + '∇', + ' ', + '–', + '≠', + '∋', + '¬', + '∉', + '⊄', + 'Ñ', + 'ñ', + 'Ν', + 'ν', + 'Ó', + 'ó', + 'Ô', + 'ô', + 'Œ', + 'œ', + 'Ò', + 'ò', + '‾', + 'Ω', + 'ω', + 'Ο', + 'ο', + '⊕', + '∨', + 'ª', + 'º', + 'Ø', + 'ø', + 'Õ', + 'õ', + '⊗', + 'Ö', + 'ö', + '¶', + '∂', + '‰', + '⊥', + 'Φ', + 'φ', + 'Π', + 'π', + 'ϖ', + '±', + '£', + '′', + '″', + '∏', + '∝', + 'Ψ', + 'ψ', + '√', + '〉', + '»', + '→', + '⇒', + '⌉', + '”', + 'ℜ', + '®', + '⌋', + 'Ρ', + 'ρ', + '‏', + '›', + '’', + '‚', + 'Š', + 'š', + '⋅', + '§', + '­', + 'Σ', + 'σ', + 'ς', + '∼', + '♠', + '⊂', + '⊆', + '∑', + '¹', + '²', + '³', + '⊃', + '⊇', + 'ß', + 'Τ', + 'τ', + '∴', + 'Θ', + 'θ', + 'ϑ', + ' ', + 'Þ', + 'þ', + '˜', + '×', + '™', + 'Ú', + 'ú', + '↑', + '⇑', + 'Û', + 'û', + 'Ù', + 'ù', + '¨', + 'ϒ', + 'Υ', + 'υ', + 'Ü', + 'ü', + '℘', + 'Ξ', + 'ξ', + 'Ý', + 'ý', + '¥', + 'ÿ', + 'Ÿ', + 'Ζ', + 'ζ', + '‍', + '‌', + '>', + '<', + '"' + ), + $str + ); + } - return $str; - } + return $str; + } } -if ( ! function_exists('clean_allowfullscreen')) { - /** - * Function clean_allowfullscreen - * - * @param $att - * - * @return array|mixed|string|string[] - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 16/02/2023 55:46 - */ - function clean_allowfullscreen($att = '') - { - return clean_youtube_allow_fullscreen($att); - } +if (!function_exists('clean_allowfullscreen')) { + /** + * Function clean_allowfullscreen + * + * @param $att + * + * @return array|mixed|string|string[] + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 16/02/2023 55:46 + */ + function clean_allowfullscreen($att = '') + { + return clean_youtube_allow_fullscreen($att); + } } -if ( ! function_exists('clean_text')) { - /** - * Function clean_text - * - * @param string $text - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 12/10/2020 36:25 - */ - function clean_text($text = '') - { - if (empty($text)) { - return $text; - } - $output = trim($text); - if ($output !== '') { - $output = convert_string_utf8_to_vietnamese($output); - $output = clean_allowfullscreen($output); - $output = trim($output); - } +if (!function_exists('clean_text')) { + /** + * Function clean_text + * + * @param string $text + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 12/10/2020 36:25 + */ + function clean_text($text = '') + { + if (empty($text)) { + return $text; + } + $output = trim($text); + if ($output !== '') { + $output = convert_string_utf8_to_vietnamese($output); + $output = clean_allowfullscreen($output); + $output = trim($output); + } - return $output; - } + return $output; + } } -if ( ! function_exists('clean_title')) { - /** - * Function clean_title - * - * @param mixed $text - * - * @return string|null - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 12/10/2020 36:32 - */ - function clean_title($text) - { - if (empty($text)) { - return $text; - } - $output = trim($text); - if ($output !== '') { - $output = clean_text($output); - $output = strip_tags($output); - if (function_exists('html_escape')) { - $output = html_escape($output); - } - $output = trim($output); - } +if (!function_exists('clean_title')) { + /** + * Function clean_title + * + * @param mixed $text + * + * @return string|null + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 12/10/2020 36:32 + */ + function clean_title($text) + { + if (empty($text)) { + return $text; + } + $output = trim($text); + if ($output !== '') { + $output = clean_text($output); + $output = strip_tags($output); + if (function_exists('html_escape')) { + $output = html_escape($output); + } + $output = trim($output); + } - return $output; - } + return $output; + } } -if ( ! function_exists('clean_text_mobile')) { - /** - * Function clean_text_mobile - * - * @param string $text - * - * @return string|string[] - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 12/10/2020 36:37 - */ - function clean_text_mobile($text = '') - { - if (empty($text)) { - return $text; - } - $output = $text; - if ($output !== '') { - $output = clean_text($output); - $output = str_replace( - array( - 'width: 100px', - 'width: 200px', - 'width: 300px', - 'width: 400px', - 'width: 420px', - 'width: 450px', - 'width: 480px', - 'width: 500px', - 'width: 520px', - 'width: 530px', - 'width: 550px', - 'width: 560px', - 'width: 580px', - 'width: 600px', - 'width: 620px', - 'width: 630px', - 'width: 640px', - 'width: 650px', - 'width: 660px', - 'width: 670px', - 'width: 680px', - 'width: 690px', - 'width: 700px', - 'width: 720px', - 'width: 730px', - 'width: 740px', - 'width: 750px', - 'width: 760px', - 'width: 770px', - 'width: 780px', - 'width: 790px', - 'width: 800px', - 'width: 820px', - 'width: 830px', - 'width: 840px', - 'width: 850px', - 'width: 860px', - 'width: 870px', - 'width: 880px', - 'width: 890px', - 'width: 890px', - 'width: 900px', - 'width: 920px', - 'width: 930px', - 'width: 940px', - 'width: 950px', - 'width: 960px', - 'width: 970px', - 'width: 980px', - 'width: 990px' - ), - 'width: 100%', - $output - ); - } +if (!function_exists('clean_text_mobile')) { + /** + * Function clean_text_mobile + * + * @param string $text + * + * @return string|string[] + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 12/10/2020 36:37 + */ + function clean_text_mobile($text = '') + { + if (empty($text)) { + return $text; + } + $output = $text; + if ($output !== '') { + $output = clean_text($output); + $output = str_replace( + array( + 'width: 100px', + 'width: 200px', + 'width: 300px', + 'width: 400px', + 'width: 420px', + 'width: 450px', + 'width: 480px', + 'width: 500px', + 'width: 520px', + 'width: 530px', + 'width: 550px', + 'width: 560px', + 'width: 580px', + 'width: 600px', + 'width: 620px', + 'width: 630px', + 'width: 640px', + 'width: 650px', + 'width: 660px', + 'width: 670px', + 'width: 680px', + 'width: 690px', + 'width: 700px', + 'width: 720px', + 'width: 730px', + 'width: 740px', + 'width: 750px', + 'width: 760px', + 'width: 770px', + 'width: 780px', + 'width: 790px', + 'width: 800px', + 'width: 820px', + 'width: 830px', + 'width: 840px', + 'width: 850px', + 'width: 860px', + 'width: 870px', + 'width: 880px', + 'width: 890px', + 'width: 890px', + 'width: 900px', + 'width: 920px', + 'width: 930px', + 'width: 940px', + 'width: 950px', + 'width: 960px', + 'width: 970px', + 'width: 980px', + 'width: 990px' + ), + 'width: 100%', + $output + ); + } - return $output; - } + return $output; + } } -if ( ! function_exists('bodautru')) { - /** - * Function bodautru - * - * @param string $string - * - * @return array|string|string[] - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 09/11/2021 03:17 - */ - function bodautru($string = '') - { - if (empty($string)) { - return $string; - } - $output = $string; - if ($output !== '') { - $output = str_replace('-', '', $output); - } +if (!function_exists('bodautru')) { + /** + * Function bodautru + * + * @param string $string + * + * @return array|string|string[] + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 09/11/2021 03:17 + */ + function bodautru($string = '') + { + if (empty($string)) { + return $string; + } + $output = $string; + if ($output !== '') { + $output = str_replace('-', '', $output); + } - return $output; - } + return $output; + } } -if ( ! function_exists('bodaunhay')) { - /** - * Function bodaunhay - * - * @param string $string - * - * @return array|string|string[] - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 09/11/2021 03:23 - */ - function bodaunhay($string = '') - { - if (empty($string)) { - return $string; - } - $output = $string; - if ($output !== '') { - $output = str_replace(array('"', "'"), '', $output); - } +if (!function_exists('bodaunhay')) { + /** + * Function bodaunhay + * + * @param string $string + * + * @return array|string|string[] + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 09/11/2021 03:23 + */ + function bodaunhay($string = '') + { + if (empty($string)) { + return $string; + } + $output = $string; + if ($output !== '') { + $output = str_replace(array('"', "'"), '', $output); + } - return $output; - } + return $output; + } } -if ( ! function_exists('searchs_snippets')) { - /** - * Function searchs_snippets - * - * @param string $keywords - * - * @return array|string|string[] - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 09/11/2021 03:28 - */ - function searchs_snippets($keywords = '') - { - if (empty($keywords)) { - return $keywords; - } - $output = $keywords; - if ($output !== '') { - $output = urldecode($output); - $output = trim($output); - $output = bodaunhay($output); - $output = str_replace(array('%20', ' ', ' - ', '---', '--', '-', '_'), '+', $output); - } +if (!function_exists('searchs_snippets')) { + /** + * Function searchs_snippets + * + * @param string $keywords + * + * @return array|string|string[] + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 09/11/2021 03:28 + */ + function searchs_snippets($keywords = '') + { + if (empty($keywords)) { + return $keywords; + } + $output = $keywords; + if ($output !== '') { + $output = urldecode($output); + $output = trim($output); + $output = bodaunhay($output); + $output = str_replace(array('%20', ' ', ' - ', '---', '--', '-', '_'), '+', $output); + } - return $output; - } + return $output; + } } -if ( ! function_exists('tags_snippets')) { - /** - * Function tags_snippets - * - * @param string $tags - * - * @return array|string|string[] - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 09/11/2021 03:35 - */ - function tags_snippets($tags = '') - { - if (empty($tags)) { - return $tags; - } - $output = $tags; - if ($output !== '') { - $output = urldecode($output); - $output = trim($output); - $output = bodaunhay($output); - $output = str_replace(array('%20', ' ', '+', '_'), '-', $output); - // $output = getPermalinksSEO($output); - } +if (!function_exists('tags_snippets')) { + /** + * Function tags_snippets + * + * @param string $tags + * + * @return array|string|string[] + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 09/11/2021 03:35 + */ + function tags_snippets($tags = '') + { + if (empty($tags)) { + return $tags; + } + $output = $tags; + if ($output !== '') { + $output = urldecode($output); + $output = trim($output); + $output = bodaunhay($output); + $output = str_replace(array('%20', ' ', '+', '_'), '-', $output); + // $output = getPermalinksSEO($output); + } - return $output; - } + return $output; + } } -if ( ! function_exists('tags_clean')) { - /** - * Function tags_clean - * - * @param string $tags - * - * @return array|string|string[] - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 09/11/2021 03:40 - */ - function tags_clean($tags = '') - { - if (empty($tags)) { - return $tags; - } - $output = $tags; - if ($output !== '') { - $output = urldecode($output); - $output = trim($output); - $output = bodaunhay($output); - $output = str_replace(array('%20', '+', '-', '_'), ' ', $output); - } +if (!function_exists('tags_clean')) { + /** + * Function tags_clean + * + * @param string $tags + * + * @return array|string|string[] + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 09/11/2021 03:40 + */ + function tags_clean($tags = '') + { + if (empty($tags)) { + return $tags; + } + $output = $tags; + if ($output !== '') { + $output = urldecode($output); + $output = trim($output); + $output = bodaunhay($output); + $output = str_replace(array('%20', '+', '-', '_'), ' ', $output); + } - return $output; - } + return $output; + } } -if ( ! function_exists('highlight_keyword_phrase')) { - /** - * Keyword Highlighter - * - * Highlights a keyword within a text string - * - * @param string $string the text string - * @param string $keyword the phrase you'd like to highlight - * @param string $tag_open the opening tag to precede the phrase with - * @param string $tag_close the closing tag to end the phrase with - * - * @return string - */ - function highlight_keyword_phrase($string, $keyword, $tag_open = '', $tag_close = '') - { - return highlight_keyword($string, $keyword, $tag_open, $tag_close); - } +if (!function_exists('highlight_keyword_phrase')) { + /** + * Keyword Highlighter + * + * Highlights a keyword within a text string + * + * @param string $string the text string + * @param string $keyword the phrase you'd like to highlight + * @param string $tag_open the opening tag to precede the phrase with + * @param string $tag_close the closing tag to end the phrase with + * + * @return string + */ + function highlight_keyword_phrase($string, $keyword, $tag_open = '', $tag_close = '') + { + return highlight_keyword($string, $keyword, $tag_open, $tag_close); + } } -if ( ! function_exists('format_keyword_highlight_phrase')) { - /** - * Function format_keyword_highlight_phrase - * - * @param $keyword - * @param $page - * - * @return mixed|string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 16/02/2023 55:02 - */ - function format_keyword_highlight_phrase($keyword, $page) - { - return format_keyword_for_highlight_keyword($keyword, $page); - } +if (!function_exists('format_keyword_highlight_phrase')) { + /** + * Function format_keyword_highlight_phrase + * + * @param $keyword + * @param $page + * + * @return mixed|string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 16/02/2023 55:02 + */ + function format_keyword_highlight_phrase($keyword, $page) + { + return format_keyword_for_highlight_keyword($keyword, $page); + } } diff --git a/helpers/tinyurl_helper.php b/helpers/tinyurl_helper.php index 8f3343e..d9d7c5d 100644 --- a/helpers/tinyurl_helper.php +++ b/helpers/tinyurl_helper.php @@ -8,19 +8,19 @@ * Date: 09/15/2021 * Time: 00:23 */ -if ( ! function_exists('short_url_with_tinyurl')) { - /** - * Function short_url_with_tinyurl - * - * @param string $longUrl - * - * @return bool|string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 09/15/2021 29:39 - */ - function short_url_with_tinyurl($longUrl = '') - { - return sendSimpleGetRequest('https://tinyurl.com/api-create.php', array('url' => $longUrl)); - } +if (!function_exists('short_url_with_tinyurl')) { + /** + * Function short_url_with_tinyurl + * + * @param string $longUrl + * + * @return bool|string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 09/15/2021 29:39 + */ + function short_url_with_tinyurl($longUrl = '') + { + return sendSimpleGetRequest('https://tinyurl.com/api-create.php', array('url' => $longUrl)); + } } diff --git a/helpers/url_helper.php b/helpers/url_helper.php index c245890..a833590 100644 --- a/helpers/url_helper.php +++ b/helpers/url_helper.php @@ -8,1585 +8,1585 @@ * Date: 09/11/2021 * Time: 09:04 */ -if ( ! function_exists('share_url')) { - /** - * Function share_url - * - * @param string $href - * @param string $platform - * @param string $app_id - * @param string $redirect - * @param string $display - * @param string $images - * @param string $title - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 09/11/2021 05:50 - */ - function share_url( - $href = '', - $platform = '', - $app_id = '', - $redirect = '', - $display = '', - $images = '', - $title = '' - ) { - $baseUrl = function_exists('base_url') ? base_url() : ''; - $share_link = $href === '' ? urlencode($baseUrl) : urlencode($href); - if (empty($redirect)) { - $redirect_link = urlencode($baseUrl); - } else { - $redirect_link = urlencode($redirect); - } - if ($platform === 'fb_share') { - if ($display !== '') { - $share_url = 'https://www.facebook.com/dialog/share?' . http_build_query( - array( - 'app_id' => $app_id, - 'display' => $display, - 'href' => $share_link, - 'redirect_uri' => $redirect_link - ) - ); - } else { - $share_url = 'https://www.facebook.com/dialog/share?' . http_build_query( - array('app_id' => $app_id, 'href' => $share_link, 'redirect_uri' => $redirect_link) - ); - } - } elseif ($platform === 'fb_send') { - if ($display !== '') { - $share_url = 'https://www.facebook.com/dialog/send?app_id=' . $app_id . '&display=' . $display . '&link=' . $share_link . '&redirect_uri=' . $redirect_link; - } else { - $share_url = 'https://www.facebook.com/dialog/send?app_id=' . $app_id . '&link=' . $share_link . '&redirect_uri=' . $redirect_link; - } - } elseif ($platform === 'twitter') { - $share_url = 'https://twitter.com/home?status=' . $share_link; - } elseif ($platform === 'googleplus') { - $share_url = 'https://plus.google.com/share?url=' . $share_link; - } elseif ($platform === 'pinterest') { - $share_url = 'https://pinterest.com/pin/create/button/?url=' . $share_link . '&media=' . $images . '&description=' . $title; - } elseif ($platform === 'linkedin') { - $share_url = 'https://www.linkedin.com/shareArticle?mini=true&url=%3Ca%20href=%22https%3A//www.linkedin.com/shareArticle?mini=true%26url=' . $share_link . '%26title=%25C3%25A1df%26summary=%25C3%25A1%26source=TV%2520News%22%3EShare%20on%20LinkedIn%3C/a%3E&title=' . $title . '&summary=&source=TV%20News'; - } else { - $share_url = $share_link; - } +if (!function_exists('share_url')) { + /** + * Function share_url + * + * @param string $href + * @param string $platform + * @param string $app_id + * @param string $redirect + * @param string $display + * @param string $images + * @param string $title + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 09/11/2021 05:50 + */ + function share_url( + $href = '', + $platform = '', + $app_id = '', + $redirect = '', + $display = '', + $images = '', + $title = '' + ) { + $baseUrl = function_exists('base_url') ? base_url() : ''; + $share_link = $href === '' ? urlencode($baseUrl) : urlencode($href); + if (empty($redirect)) { + $redirect_link = urlencode($baseUrl); + } else { + $redirect_link = urlencode($redirect); + } + if ($platform === 'fb_share') { + if ($display !== '') { + $share_url = 'https://www.facebook.com/dialog/share?' . http_build_query( + array( + 'app_id' => $app_id, + 'display' => $display, + 'href' => $share_link, + 'redirect_uri' => $redirect_link + ) + ); + } else { + $share_url = 'https://www.facebook.com/dialog/share?' . http_build_query( + array('app_id' => $app_id, 'href' => $share_link, 'redirect_uri' => $redirect_link) + ); + } + } elseif ($platform === 'fb_send') { + if ($display !== '') { + $share_url = 'https://www.facebook.com/dialog/send?app_id=' . $app_id . '&display=' . $display . '&link=' . $share_link . '&redirect_uri=' . $redirect_link; + } else { + $share_url = 'https://www.facebook.com/dialog/send?app_id=' . $app_id . '&link=' . $share_link . '&redirect_uri=' . $redirect_link; + } + } elseif ($platform === 'twitter') { + $share_url = 'https://twitter.com/home?status=' . $share_link; + } elseif ($platform === 'googleplus') { + $share_url = 'https://plus.google.com/share?url=' . $share_link; + } elseif ($platform === 'pinterest') { + $share_url = 'https://pinterest.com/pin/create/button/?url=' . $share_link . '&media=' . $images . '&description=' . $title; + } elseif ($platform === 'linkedin') { + $share_url = 'https://www.linkedin.com/shareArticle?mini=true&url=%3Ca%20href=%22https%3A//www.linkedin.com/shareArticle?mini=true%26url=' . $share_link . '%26title=%25C3%25A1df%26summary=%25C3%25A1%26source=TV%2520News%22%3EShare%20on%20LinkedIn%3C/a%3E&title=' . $title . '&summary=&source=TV%20News'; + } else { + $share_url = $share_link; + } - return $share_url; - } + return $share_url; + } } -if ( ! function_exists('encodeId_Url_byHungDEV')) { - /** - * Function encodeId_Url_byHungDEV - * - * Mã hóa Url ID của bài viết, tăng tính bảo mật - * Sử dụng Chuỗi sau khi đã Encode để show ra Url - * - * @param $id - * - * @return array|int|string|string[] - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 09/11/2021 05:58 - */ - function encodeId_Url_byHungDEV($id) - { - $id += 1112223333; +if (!function_exists('encodeId_Url_byHungDEV')) { + /** + * Function encodeId_Url_byHungDEV + * + * Mã hóa Url ID của bài viết, tăng tính bảo mật + * Sử dụng Chuỗi sau khi đã Encode để show ra Url + * + * @param $id + * + * @return array|int|string|string[] + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 09/11/2021 05:58 + */ + function encodeId_Url_byHungDEV($id) + { + $id += 1112223333; - return str_replace( - array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'), - array('E', 'R', 'M', 'N', 'J', 'I', 'Z', 'K', 'L', 'O'), - $id - ); - } + return str_replace( + array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'), + array('E', 'R', 'M', 'N', 'J', 'I', 'Z', 'K', 'L', 'O'), + $id + ); + } } -if ( ! function_exists('decodeId_Url_byHungDEV')) { - /** - * Function decodeId_Url_byHungDEV - * - * Giải mãi Url ID của bài viết để lấy ID gốc - * Sử dụng ID gốc này để truy vấn vào server lấy thông tin - * - * @param $id - * - * @return array|int|string|string[] - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 09/11/2021 06:42 - */ - function decodeId_Url_byHungDEV($id) - { - $id = mb_strtoupper($id); - $id = str_replace( - array('E', 'R', 'M', 'N', 'J', 'I', 'Z', 'K', 'L', 'O'), - array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'), - $id - ); - $id -= 1112223333; +if (!function_exists('decodeId_Url_byHungDEV')) { + /** + * Function decodeId_Url_byHungDEV + * + * Giải mãi Url ID của bài viết để lấy ID gốc + * Sử dụng ID gốc này để truy vấn vào server lấy thông tin + * + * @param $id + * + * @return array|int|string|string[] + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 09/11/2021 06:42 + */ + function decodeId_Url_byHungDEV($id) + { + $id = mb_strtoupper($id); + $id = str_replace( + array('E', 'R', 'M', 'N', 'J', 'I', 'Z', 'K', 'L', 'O'), + array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'), + $id + ); + $id -= 1112223333; - return $id; - } + return $id; + } } -if ( ! function_exists('convertToLatin')) { - /** - * Function convertToLatin - * - * Hàm dùng để convert các ký tự có dấu thành không dấu - * Dùng tốt cho các chức năng SEO - * vì nhiều engine không hiểu được dấu tiếng Việt - * nên cần phải bỏ dấu tiếng Việt đi - * - * @param string $string - * @param false $alphabetOnly - * @param bool $toLower - * - * @return array|string|string[] - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 09/11/2021 07:43 - */ - function convertToLatin($string = '', $alphabetOnly = false, $toLower = true) - { - $output = $string; - if ($output !== '') { - //Tien hanh xu ly bo dau o day - $search = array( - 'á', - 'à', - 'ả', - 'ã', - 'ạ', - 'ă', - 'ắ', - 'ằ', - 'ẳ', - 'ẵ', - 'ặ', - 'â', - 'ấ', - 'ầ', - 'ẩ', - 'ẫ', - 'ậ', - 'đ', - 'é', - 'è', - 'ẻ', - 'ẽ', - 'ẹ', - 'ê', - 'ế', - 'ề', - 'ể', - 'ễ', - 'ệ', - 'í', - 'ì', - 'ỉ', - 'ĩ', - 'ị', - 'ó', - 'ò', - 'ỏ', - 'õ', - 'ọ', - 'ô', - 'ố', - 'ồ', - 'ổ', - 'ỗ', - 'ộ', - 'ơ', - 'ớ', - 'ờ', - 'ở', - 'ỡ', - 'ợ', - 'ú', - 'ù', - 'ủ', - 'ũ', - 'ụ', - 'ư', - 'ứ', - 'ừ', - 'ử', - 'ữ', - 'ự', - 'ý', - 'ỳ', - 'ỷ', - 'ỹ', - 'ỵ', - 'Á', - 'À', - 'Ả', - 'Ã', - 'Ạ', - 'Ă', - 'Ắ', - 'Ằ', - 'Ẳ', - 'Ẵ', - 'Ặ', - 'Â', - 'Ấ', - 'Ầ', - 'Ẩ', - 'Ẫ', - 'Ậ', - 'Đ', - 'É', - 'È', - 'Ẻ', - 'Ẽ', - 'Ẹ', - 'Ê', - 'Ế', - 'Ề', - 'Ể', - 'Ễ', - 'Ệ', - 'Í', - 'Ì', - 'Ỉ', - 'Ĩ', - 'Ị', - 'Ó', - 'Ò', - 'Ỏ', - 'Õ', - 'Ọ', - 'Ô', - 'Ố', - 'Ồ', - 'Ổ', - 'Ỗ', - 'Ộ', - 'Ơ', - 'Ớ', - 'Ờ', - 'Ở', - 'Ỡ', - 'Ợ', - 'Ú', - 'Ù', - 'Ủ', - 'Ũ', - 'Ụ', - 'Ư', - 'Ứ', - 'Ừ', - 'Ử', - 'Ữ', - 'Ự', - 'Ý', - 'Ỳ', - 'Ỷ', - 'Ỹ', - 'Ỵ' - ); - $search2 = array( - 'á', - 'à', - 'ả', - 'ã', - 'ạ', - 'ă', - 'ắ', - 'ằ', - 'ẳ', - 'ẵ', - 'ặ', - 'â', - 'ấ', - 'ầ', - 'ẩ', - 'ẫ', - 'ậ', - 'đ', - 'é', - 'è', - 'ẻ', - 'ẽ', - 'ẹ', - 'ê', - 'ế', - 'ề', - 'ể', - 'ễ', - 'ệ', - 'í', - 'ì', - 'ỉ', - 'ĩ', - 'ị', - 'ó', - 'ò', - 'ỏ', - 'õ', - 'ọ', - 'ó ', - 'ô', - 'ố', - 'ồ', - 'ổ', - 'ỗ', - 'ộ', - 'ơ', - 'ớ', - 'ờ', - 'ở', - 'ỡ', - 'ợ', - 'ú', - 'ù', - 'ủ', - 'ũ', - 'ụ', - 'u', - 'ư', - 'ứ', - 'ừ', - 'ử', - 'ữ', - 'ự', - 'ý', - 'ỳ', - 'ỷ', - 'ỹ', - 'ỵ', - 'Á', - 'À', - 'Ả', - 'Ã', - 'Ạ', - 'Ă', - 'Ắ', - 'Ằ', - 'Ẳ', - 'Ẵ', - 'Ặ', - 'Â', - 'Ấ', - 'Ầ', - 'Ẩ', - 'Ẫ', - 'Ậ', - 'Đ', - 'É', - 'È', - 'Ẻ', - 'Ẽ', - 'Ẹ', - 'Ê', - 'Ế', - 'Ề', - 'Ể', - 'Ễ', - 'Ệ', - 'Í', - 'Ì', - 'Ỉ', - 'Ĩ', - 'Ị', - 'Ó', - 'Ò', - 'Ỏ', - 'Õ', - 'Ọ', - 'Ô', - 'Ố', - 'Ồ', - 'Ổ', - 'Ỗ', - 'Ộ', - 'Ơ', - 'Ớ', - 'Ờ', - 'Ở', - 'Ỡ', - 'Ợ', - 'Ú', - 'Ù', - 'Ủ', - 'Ũ', - 'Ụ', - 'Ư', - 'Ứ', - 'Ừ', - 'Ử', - 'Ữ', - 'Ự', - 'Ý', - 'Ỳ', - 'Ỷ', - 'Ỹ', - 'Ỵ' - ); - $replace = array( - 'a', - 'a', - 'a', - 'a', - 'a', - 'a', - 'a', - 'a', - 'a', - 'a', - 'a', - 'a', - 'a', - 'a', - 'a', - 'a', - 'a', - 'd', - 'e', - 'e', - 'e', - 'e', - 'e', - 'e', - 'e', - 'e', - 'e', - 'e', - 'e', - 'i', - 'i', - 'i', - 'i', - 'i', - 'o', - 'o', - 'o', - 'o', - 'o', - 'o', - 'o', - 'o', - 'o', - 'o', - 'o', - 'o', - 'o', - 'o', - 'o', - 'o', - 'o', - 'u', - 'u', - 'u', - 'u', - 'u', - 'u', - 'u', - 'u', - 'u', - 'u', - 'u', - 'y', - 'y', - 'y', - 'y', - 'y', - 'A', - 'A', - 'A', - 'A', - 'A', - 'A', - 'A', - 'A', - 'A', - 'A', - 'A', - 'A', - 'A', - 'A', - 'A', - 'A', - 'A', - 'D', - 'E', - 'E', - 'E', - 'E', - 'E', - 'E', - 'E', - 'E', - 'E', - 'E', - 'E', - 'I', - 'I', - 'I', - 'I', - 'I', - 'O', - 'O', - 'O', - 'O', - 'O', - 'O', - 'O', - 'O', - 'O', - 'O', - 'O', - 'O', - 'O', - 'O', - 'O', - 'O', - 'O', - 'U', - 'U', - 'U', - 'U', - 'U', - 'U', - 'U', - 'U', - 'U', - 'U', - 'U', - 'Y', - 'Y', - 'Y', - 'Y', - 'Y' - ); - $output = str_replace(array($search, $search2), array($replace, $replace), $output); - if ($alphabetOnly) { - $output = alphabetOnly($output); - } - if ($toLower) { - $output = mb_strtolower($output); - } - } +if (!function_exists('convertToLatin')) { + /** + * Function convertToLatin + * + * Hàm dùng để convert các ký tự có dấu thành không dấu + * Dùng tốt cho các chức năng SEO + * vì nhiều engine không hiểu được dấu tiếng Việt + * nên cần phải bỏ dấu tiếng Việt đi + * + * @param string $string + * @param false $alphabetOnly + * @param bool $toLower + * + * @return array|string|string[] + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 09/11/2021 07:43 + */ + function convertToLatin($string = '', $alphabetOnly = false, $toLower = true) + { + $output = $string; + if ($output !== '') { + //Tien hanh xu ly bo dau o day + $search = array( + 'á', + 'à', + 'ả', + 'ã', + 'ạ', + 'ă', + 'ắ', + 'ằ', + 'ẳ', + 'ẵ', + 'ặ', + 'â', + 'ấ', + 'ầ', + 'ẩ', + 'ẫ', + 'ậ', + 'đ', + 'é', + 'è', + 'ẻ', + 'ẽ', + 'ẹ', + 'ê', + 'ế', + 'ề', + 'ể', + 'ễ', + 'ệ', + 'í', + 'ì', + 'ỉ', + 'ĩ', + 'ị', + 'ó', + 'ò', + 'ỏ', + 'õ', + 'ọ', + 'ô', + 'ố', + 'ồ', + 'ổ', + 'ỗ', + 'ộ', + 'ơ', + 'ớ', + 'ờ', + 'ở', + 'ỡ', + 'ợ', + 'ú', + 'ù', + 'ủ', + 'ũ', + 'ụ', + 'ư', + 'ứ', + 'ừ', + 'ử', + 'ữ', + 'ự', + 'ý', + 'ỳ', + 'ỷ', + 'ỹ', + 'ỵ', + 'Á', + 'À', + 'Ả', + 'Ã', + 'Ạ', + 'Ă', + 'Ắ', + 'Ằ', + 'Ẳ', + 'Ẵ', + 'Ặ', + 'Â', + 'Ấ', + 'Ầ', + 'Ẩ', + 'Ẫ', + 'Ậ', + 'Đ', + 'É', + 'È', + 'Ẻ', + 'Ẽ', + 'Ẹ', + 'Ê', + 'Ế', + 'Ề', + 'Ể', + 'Ễ', + 'Ệ', + 'Í', + 'Ì', + 'Ỉ', + 'Ĩ', + 'Ị', + 'Ó', + 'Ò', + 'Ỏ', + 'Õ', + 'Ọ', + 'Ô', + 'Ố', + 'Ồ', + 'Ổ', + 'Ỗ', + 'Ộ', + 'Ơ', + 'Ớ', + 'Ờ', + 'Ở', + 'Ỡ', + 'Ợ', + 'Ú', + 'Ù', + 'Ủ', + 'Ũ', + 'Ụ', + 'Ư', + 'Ứ', + 'Ừ', + 'Ử', + 'Ữ', + 'Ự', + 'Ý', + 'Ỳ', + 'Ỷ', + 'Ỹ', + 'Ỵ' + ); + $search2 = array( + 'á', + 'à', + 'ả', + 'ã', + 'ạ', + 'ă', + 'ắ', + 'ằ', + 'ẳ', + 'ẵ', + 'ặ', + 'â', + 'ấ', + 'ầ', + 'ẩ', + 'ẫ', + 'ậ', + 'đ', + 'é', + 'è', + 'ẻ', + 'ẽ', + 'ẹ', + 'ê', + 'ế', + 'ề', + 'ể', + 'ễ', + 'ệ', + 'í', + 'ì', + 'ỉ', + 'ĩ', + 'ị', + 'ó', + 'ò', + 'ỏ', + 'õ', + 'ọ', + 'ó ', + 'ô', + 'ố', + 'ồ', + 'ổ', + 'ỗ', + 'ộ', + 'ơ', + 'ớ', + 'ờ', + 'ở', + 'ỡ', + 'ợ', + 'ú', + 'ù', + 'ủ', + 'ũ', + 'ụ', + 'u', + 'ư', + 'ứ', + 'ừ', + 'ử', + 'ữ', + 'ự', + 'ý', + 'ỳ', + 'ỷ', + 'ỹ', + 'ỵ', + 'Á', + 'À', + 'Ả', + 'Ã', + 'Ạ', + 'Ă', + 'Ắ', + 'Ằ', + 'Ẳ', + 'Ẵ', + 'Ặ', + 'Â', + 'Ấ', + 'Ầ', + 'Ẩ', + 'Ẫ', + 'Ậ', + 'Đ', + 'É', + 'È', + 'Ẻ', + 'Ẽ', + 'Ẹ', + 'Ê', + 'Ế', + 'Ề', + 'Ể', + 'Ễ', + 'Ệ', + 'Í', + 'Ì', + 'Ỉ', + 'Ĩ', + 'Ị', + 'Ó', + 'Ò', + 'Ỏ', + 'Õ', + 'Ọ', + 'Ô', + 'Ố', + 'Ồ', + 'Ổ', + 'Ỗ', + 'Ộ', + 'Ơ', + 'Ớ', + 'Ờ', + 'Ở', + 'Ỡ', + 'Ợ', + 'Ú', + 'Ù', + 'Ủ', + 'Ũ', + 'Ụ', + 'Ư', + 'Ứ', + 'Ừ', + 'Ử', + 'Ữ', + 'Ự', + 'Ý', + 'Ỳ', + 'Ỷ', + 'Ỹ', + 'Ỵ' + ); + $replace = array( + 'a', + 'a', + 'a', + 'a', + 'a', + 'a', + 'a', + 'a', + 'a', + 'a', + 'a', + 'a', + 'a', + 'a', + 'a', + 'a', + 'a', + 'd', + 'e', + 'e', + 'e', + 'e', + 'e', + 'e', + 'e', + 'e', + 'e', + 'e', + 'e', + 'i', + 'i', + 'i', + 'i', + 'i', + 'o', + 'o', + 'o', + 'o', + 'o', + 'o', + 'o', + 'o', + 'o', + 'o', + 'o', + 'o', + 'o', + 'o', + 'o', + 'o', + 'o', + 'u', + 'u', + 'u', + 'u', + 'u', + 'u', + 'u', + 'u', + 'u', + 'u', + 'u', + 'y', + 'y', + 'y', + 'y', + 'y', + 'A', + 'A', + 'A', + 'A', + 'A', + 'A', + 'A', + 'A', + 'A', + 'A', + 'A', + 'A', + 'A', + 'A', + 'A', + 'A', + 'A', + 'D', + 'E', + 'E', + 'E', + 'E', + 'E', + 'E', + 'E', + 'E', + 'E', + 'E', + 'E', + 'I', + 'I', + 'I', + 'I', + 'I', + 'O', + 'O', + 'O', + 'O', + 'O', + 'O', + 'O', + 'O', + 'O', + 'O', + 'O', + 'O', + 'O', + 'O', + 'O', + 'O', + 'O', + 'U', + 'U', + 'U', + 'U', + 'U', + 'U', + 'U', + 'U', + 'U', + 'U', + 'U', + 'Y', + 'Y', + 'Y', + 'Y', + 'Y' + ); + $output = str_replace(array($search, $search2), array($replace, $replace), $output); + if ($alphabetOnly) { + $output = alphabetOnly($output); + } + if ($toLower) { + $output = mb_strtolower($output); + } + } - return $output; - } + return $output; + } } -if ( ! function_exists('specialCharToNormalChar')) { - /** - * Function specialCharToNormalChar - * - * Chuyển đổi ký tự đặc biệt thành char - * - * @param string $string - * - * @return array|string|string[] - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 09/11/2021 08:00 - */ - function specialCharToNormalChar($string = '') - { - $output = $string; - if ($output !== '') { - //Tien hanh xu ly bo dau o day - $search = array( - 'á', - 'à', - 'ả', - 'ã', - 'ạ', - 'ă', - 'ắ', - 'ằ', - 'ẳ', - 'ẵ', - 'ặ', - 'â', - 'ấ', - 'ầ', - 'ẩ', - 'ẫ', - 'ậ', - 'đ', - 'é', - 'è', - 'ẻ', - 'ẽ', - 'ẹ', - 'ê', - 'ế', - 'ề', - 'ể', - 'ễ', - 'ệ', - 'í', - 'ì', - 'ỉ', - 'ĩ', - 'ị', - 'ó', - 'ò', - 'ỏ', - 'õ', - 'ọ', - 'ô', - 'ố', - 'ồ', - 'ổ', - 'ỗ', - 'ộ', - 'ơ', - 'ớ', - 'ờ', - 'ở', - 'ỡ', - 'ợ', - 'ú', - 'ù', - 'ủ', - 'ũ', - 'ụ', - 'ư', - 'ứ', - 'ừ', - 'ử', - 'ữ', - 'ự', - 'ý', - 'ỳ', - 'ỷ', - 'ỹ', - 'ỵ', - 'Á', - 'À', - 'Ả', - 'Ã', - 'Ạ', - 'Ă', - 'Ắ', - 'Ằ', - 'Ẳ', - 'Ẵ', - 'Ặ', - 'Â', - 'Ấ', - 'Ầ', - 'Ẩ', - 'Ẫ', - 'Ậ', - 'Đ', - 'É', - 'È', - 'Ẻ', - 'Ẽ', - 'Ẹ', - 'Ê', - 'Ế', - 'Ề', - 'Ể', - 'Ễ', - 'Ệ', - 'Í', - 'Ì', - 'Ỉ', - 'Ĩ', - 'Ị', - 'Ó', - 'Ò', - 'Ỏ', - 'Õ', - 'Ọ', - 'Ô', - 'Ố', - 'Ồ', - 'Ổ', - 'Ỗ', - 'Ộ', - 'Ơ', - 'Ớ', - 'Ờ', - 'Ở', - 'Ỡ', - 'Ợ', - 'Ú', - 'Ù', - 'Ủ', - 'Ũ', - 'Ụ', - 'Ư', - 'Ứ', - 'Ừ', - 'Ử', - 'Ữ', - 'Ự', - 'Ý', - 'Ỳ', - 'Ỷ', - 'Ỹ', - 'Ỵ' - ); - $replace = array( - 'á', - 'à', - 'ả', - 'ã', - 'ạ', - 'ă', - 'ắ', - 'ằ', - 'ẳ', - 'ẵ', - 'ặ', - 'â', - 'ấ', - 'ầ', - 'ẩ', - 'ẫ', - 'ậ', - 'đ', - 'é', - 'è', - 'ẻ', - 'ẽ', - 'ẹ', - 'ê', - 'ế', - 'ề', - 'ể', - 'ễ', - 'ệ', - 'í', - 'ì', - 'ỉ', - 'ĩ', - 'ị', - 'ó', - 'ò', - 'ỏ', - 'õ', - 'ọ', - 'ô', - 'ố', - 'ồ', - 'ổ', - 'ỗ', - 'ộ', - 'ơ', - 'ớ', - 'ờ', - 'ở', - 'ỡ', - 'ợ', - 'ú', - 'ù', - 'ủ', - 'ũ', - 'ụ', - 'ư', - 'ứ', - 'ừ', - 'ử', - 'ữ', - 'ự', - 'ý', - 'ỳ', - 'ỷ', - 'ỹ', - 'ỵ', - 'Á', - 'À', - 'Ả', - 'Ã', - 'Ạ', - 'Ă', - 'Ắ', - 'Ằ', - 'Ẳ', - 'Ẵ', - 'Ặ', - 'Â', - 'Ấ', - 'Ầ', - 'Ẩ', - 'Ẫ', - 'Ậ', - 'Đ', - 'É', - 'È', - 'Ẻ', - 'Ẽ', - 'Ẹ', - 'Ê', - 'Ế', - 'Ề', - 'Ể', - 'Ễ', - 'Ệ', - 'Í', - 'Ì', - 'Ỉ', - 'Ĩ', - 'Ị', - 'Ó', - 'Ò', - 'Ỏ', - 'Õ', - 'Ọ', - 'Ô', - 'Ố', - 'Ồ', - 'Ổ', - 'Ỗ', - 'Ộ', - 'Ơ', - 'Ớ', - 'Ờ', - 'Ở', - 'Ỡ', - 'Ợ', - 'Ú', - 'Ù', - 'Ủ', - 'Ũ', - 'Ụ', - 'Ư', - 'Ứ', - 'Ừ', - 'Ử', - 'Ữ', - 'Ự', - 'Ý', - 'Ỳ', - 'Ỷ', - 'Ỹ', - 'Ỵ' - ); - $output = str_replace($search, $replace, $output); - } +if (!function_exists('specialCharToNormalChar')) { + /** + * Function specialCharToNormalChar + * + * Chuyển đổi ký tự đặc biệt thành char + * + * @param string $string + * + * @return array|string|string[] + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 09/11/2021 08:00 + */ + function specialCharToNormalChar($string = '') + { + $output = $string; + if ($output !== '') { + //Tien hanh xu ly bo dau o day + $search = array( + 'á', + 'à', + 'ả', + 'ã', + 'ạ', + 'ă', + 'ắ', + 'ằ', + 'ẳ', + 'ẵ', + 'ặ', + 'â', + 'ấ', + 'ầ', + 'ẩ', + 'ẫ', + 'ậ', + 'đ', + 'é', + 'è', + 'ẻ', + 'ẽ', + 'ẹ', + 'ê', + 'ế', + 'ề', + 'ể', + 'ễ', + 'ệ', + 'í', + 'ì', + 'ỉ', + 'ĩ', + 'ị', + 'ó', + 'ò', + 'ỏ', + 'õ', + 'ọ', + 'ô', + 'ố', + 'ồ', + 'ổ', + 'ỗ', + 'ộ', + 'ơ', + 'ớ', + 'ờ', + 'ở', + 'ỡ', + 'ợ', + 'ú', + 'ù', + 'ủ', + 'ũ', + 'ụ', + 'ư', + 'ứ', + 'ừ', + 'ử', + 'ữ', + 'ự', + 'ý', + 'ỳ', + 'ỷ', + 'ỹ', + 'ỵ', + 'Á', + 'À', + 'Ả', + 'Ã', + 'Ạ', + 'Ă', + 'Ắ', + 'Ằ', + 'Ẳ', + 'Ẵ', + 'Ặ', + 'Â', + 'Ấ', + 'Ầ', + 'Ẩ', + 'Ẫ', + 'Ậ', + 'Đ', + 'É', + 'È', + 'Ẻ', + 'Ẽ', + 'Ẹ', + 'Ê', + 'Ế', + 'Ề', + 'Ể', + 'Ễ', + 'Ệ', + 'Í', + 'Ì', + 'Ỉ', + 'Ĩ', + 'Ị', + 'Ó', + 'Ò', + 'Ỏ', + 'Õ', + 'Ọ', + 'Ô', + 'Ố', + 'Ồ', + 'Ổ', + 'Ỗ', + 'Ộ', + 'Ơ', + 'Ớ', + 'Ờ', + 'Ở', + 'Ỡ', + 'Ợ', + 'Ú', + 'Ù', + 'Ủ', + 'Ũ', + 'Ụ', + 'Ư', + 'Ứ', + 'Ừ', + 'Ử', + 'Ữ', + 'Ự', + 'Ý', + 'Ỳ', + 'Ỷ', + 'Ỹ', + 'Ỵ' + ); + $replace = array( + 'á', + 'à', + 'ả', + 'ã', + 'ạ', + 'ă', + 'ắ', + 'ằ', + 'ẳ', + 'ẵ', + 'ặ', + 'â', + 'ấ', + 'ầ', + 'ẩ', + 'ẫ', + 'ậ', + 'đ', + 'é', + 'è', + 'ẻ', + 'ẽ', + 'ẹ', + 'ê', + 'ế', + 'ề', + 'ể', + 'ễ', + 'ệ', + 'í', + 'ì', + 'ỉ', + 'ĩ', + 'ị', + 'ó', + 'ò', + 'ỏ', + 'õ', + 'ọ', + 'ô', + 'ố', + 'ồ', + 'ổ', + 'ỗ', + 'ộ', + 'ơ', + 'ớ', + 'ờ', + 'ở', + 'ỡ', + 'ợ', + 'ú', + 'ù', + 'ủ', + 'ũ', + 'ụ', + 'ư', + 'ứ', + 'ừ', + 'ử', + 'ữ', + 'ự', + 'ý', + 'ỳ', + 'ỷ', + 'ỹ', + 'ỵ', + 'Á', + 'À', + 'Ả', + 'Ã', + 'Ạ', + 'Ă', + 'Ắ', + 'Ằ', + 'Ẳ', + 'Ẵ', + 'Ặ', + 'Â', + 'Ấ', + 'Ầ', + 'Ẩ', + 'Ẫ', + 'Ậ', + 'Đ', + 'É', + 'È', + 'Ẻ', + 'Ẽ', + 'Ẹ', + 'Ê', + 'Ế', + 'Ề', + 'Ể', + 'Ễ', + 'Ệ', + 'Í', + 'Ì', + 'Ỉ', + 'Ĩ', + 'Ị', + 'Ó', + 'Ò', + 'Ỏ', + 'Õ', + 'Ọ', + 'Ô', + 'Ố', + 'Ồ', + 'Ổ', + 'Ỗ', + 'Ộ', + 'Ơ', + 'Ớ', + 'Ờ', + 'Ở', + 'Ỡ', + 'Ợ', + 'Ú', + 'Ù', + 'Ủ', + 'Ũ', + 'Ụ', + 'Ư', + 'Ứ', + 'Ừ', + 'Ử', + 'Ữ', + 'Ự', + 'Ý', + 'Ỳ', + 'Ỷ', + 'Ỹ', + 'Ỵ' + ); + $output = str_replace($search, $replace, $output); + } - return $output; - } + return $output; + } } -if ( ! function_exists('alphabetOnly')) { - /** - * Function alphabetOnly - Loại bỏ các ký tự không phải alphabet - * - * @param string $string - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 09/11/2021 09:19 - */ - function alphabetOnly($string = '') - { - if (empty($string)) { - return $string; - } - $output = $string; - // replace no alphabet character - $output = preg_replace("/[^a-zA-Z0-9]/", "-", $output); - $output = preg_replace("/-+/", "-", $output); +if (!function_exists('alphabetOnly')) { + /** + * Function alphabetOnly - Loại bỏ các ký tự không phải alphabet + * + * @param string $string + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 09/11/2021 09:19 + */ + function alphabetOnly($string = '') + { + if (empty($string)) { + return $string; + } + $output = $string; + // replace no alphabet character + $output = preg_replace("/[^a-zA-Z0-9]/", "-", $output); + $output = preg_replace("/-+/", "-", $output); - return trim($output, '-'); - } + return trim($output, '-'); + } } -if ( ! function_exists('boDauTiengViet')) { - /** - * Function boDauTiengViet - Tính năng chả khác mịa gì codau2khongdau() - * - * @param $input_string - * - * @return array|mixed|string|string[] - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 23/02/2023 56:11 - */ - function boDauTiengViet($input_string = '') - { - $str = $input_string; - if ($str !== '') { - // Mảng tiếng Việt - $marTViet = array( - "à", - "á", - "ạ", - "ả", - "ã", - "ầ", - "ấ", - "ậ", - "ẩ", - "ẫ", - "ă", - "â", - "ằ", - "ắ", - "ặ", - "ẳ", - "ẵ", - "ă", - "è", - "é", - "ẹ", - "ẻ", - "ẽ", - "ề", - "ế", - "ệ", - "ể", - "ễ", - "ê", - "ì", - "í", - "ị", - "ỉ", - "ĩ", - "ò", - "ó", - "ọ", - "ỏ", - "õ", - "ồ", - "ố", - "ộ", - "ổ", - "ỗ", - "ô", - "ờ", - "ớ", - "ợ", - "ở", - "ỡ", - "ơ", - "ù", - "ú", - "ụ", - "ủ", - "ũ", - "ừ", - "ứ", - "ự", - "ử", - "ữ", - "ư", - "ỳ", - "ý", - "ỵ", - "ỷ", - "ỹ", - "đ", - "A", - "À", - "Á", - "Ạ", - "Ả", - "Ã", - "Ầ", - "Ấ", - "Ậ", - "Ẩ", - "Ẫ", - "Ă", - "Â", - "Ằ", - "Ắ", - "Ặ", - "Ẳ", - "Ẵ", - "Ă", - "È", - "É", - "Ẹ", - "Ẻ", - "Ẽ", - "E", - "Ề", - "Ế", - "Ệ", - "Ể", - "Ễ", - "Ê", - "I", - "Ì", - "Í", - "Ị", - "Ỉ", - "Ĩ", - "O", - "Ò", - "Ó", - "Ọ", - "Ỏ", - "Õ", - "Ồ", - "Ố", - "Ộ", - "Ổ", - "Ỗ", - "Ô", - "Ờ", - "Ớ", - "Ợ", - "Ở", - "Ỡ", - "Ơ", - "Ù", - "Ú", - "Ụ", - "Ủ", - "Ũ", - "U", - "Ừ", - "Ứ", - "Ự", - "Ử", - "Ữ", - "Ư", - "Ỳ", - "Ý", - "Ỵ", - "Ỷ", - "Ỹ", - "Y", - "Đ", - "B", - "C", - "D", - "F", - "G", - "H", - "I", - "J", - "K", - "L", - "M", - "N", - "P", - "Q", - "R", - "S", - "T", - "V", - "X", - "Y", - "Z", - "W" - ); - // Mảng ko dấu - $marKoDau = array( - "a", - "a", - "a", - "a", - "a", - "a", - "a", - "a", - "a", - "a", - "a", - "a", - "a", - "a", - "a", - "a", - "a", - "a", - "e", - "e", - "e", - "e", - "e", - "e", - "e", - "e", - "e", - "e", - "e", - "i", - "i", - "i", - "i", - "i", - "o", - "o", - "o", - "o", - "o", - "o", - "o", - "o", - "o", - "o", - "o", - "o", - "o", - "o", - "o", - "o", - "o", - "u", - "u", - "u", - "u", - "u", - "u", - "u", - "u", - "u", - "u", - "u", - "y", - "y", - "y", - "y", - "y", - "d", - "a", - "a", - "a", - "a", - "a", - "a", - "a", - "a", - "a", - "a", - "a", - "a", - "a", - "a", - "a", - "a", - "a", - "a", - "a", - "e", - "e", - "e", - "e", - "e", - "e", - "e", - "e", - "e", - "e", - "e", - "e", - "i", - "i", - "i", - "i", - "i", - "i", - "o", - "o", - "o", - "o", - "o", - "o", - "o", - "o", - "o", - "o", - "o", - "o", - "o", - "o", - "o", - "o", - "o", - "o", - "u", - "u", - "u", - "u", - "u", - "u", - "u", - "u", - "u", - "u", - "u", - "u", - "y", - "y", - "y", - "y", - "y", - "y", - "d", - "b", - "c", - "d", - "f", - "g", - "h", - "i", - "j", - "k", - "l", - "m", - "n", - "p", - "q", - "r", - "s", - "t", - "v", - "x", - "y", - "z", - "w" - ); - // Tiến hành chuyển đổi Mảng tiếng Việt thành Mảng ko dấu - // Lọc các ký tự đặc biệt - // Bỏ khoảng trắng - $str = str_replace( - array( - $marTViet, - ',', - ';', - '\'', - '"', - '(', - ')', - '.', - ':', - '…', - '[', - ']', - '|', - '\\', - '?', - "/", - "!", - "@", - "#", - "$", - "^", - "&", - "*", - "+", - "=", - "<", - ">", - "–", - '™', - '®', - '%', - '“', - '”', - '’', - '‘', - ' ' - ), - array( - $marKoDau, - '-', - '-', - '-', - '-', - '-', - '-', - '-', - '-', - '-', - '-', - '-', - '-', - '-', - '-', - '-', - '-', - '-', - '-', - '-', - '-', - '-', - '-', - '-', - '-', - '-', - '-', - '-', - '-', - '-', - '-', - '-', - '-', - '-', - '-', - '-' - ), - $str - ); - // Loại bỏ ký tự trùng lặp special (-) - while (mb_strpos($str, '--') > 0) { - $str = str_replace('--', '-', $str); - } - while (mb_strpos($str, '--') === 0) { - $str = str_replace('--', '-', $str); - } - } +if (!function_exists('boDauTiengViet')) { + /** + * Function boDauTiengViet - Tính năng chả khác mịa gì codau2khongdau() + * + * @param $input_string + * + * @return array|mixed|string|string[] + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 23/02/2023 56:11 + */ + function boDauTiengViet($input_string = '') + { + $str = $input_string; + if ($str !== '') { + // Mảng tiếng Việt + $marTViet = array( + "à", + "á", + "ạ", + "ả", + "ã", + "ầ", + "ấ", + "ậ", + "ẩ", + "ẫ", + "ă", + "â", + "ằ", + "ắ", + "ặ", + "ẳ", + "ẵ", + "ă", + "è", + "é", + "ẹ", + "ẻ", + "ẽ", + "ề", + "ế", + "ệ", + "ể", + "ễ", + "ê", + "ì", + "í", + "ị", + "ỉ", + "ĩ", + "ò", + "ó", + "ọ", + "ỏ", + "õ", + "ồ", + "ố", + "ộ", + "ổ", + "ỗ", + "ô", + "ờ", + "ớ", + "ợ", + "ở", + "ỡ", + "ơ", + "ù", + "ú", + "ụ", + "ủ", + "ũ", + "ừ", + "ứ", + "ự", + "ử", + "ữ", + "ư", + "ỳ", + "ý", + "ỵ", + "ỷ", + "ỹ", + "đ", + "A", + "À", + "Á", + "Ạ", + "Ả", + "Ã", + "Ầ", + "Ấ", + "Ậ", + "Ẩ", + "Ẫ", + "Ă", + "Â", + "Ằ", + "Ắ", + "Ặ", + "Ẳ", + "Ẵ", + "Ă", + "È", + "É", + "Ẹ", + "Ẻ", + "Ẽ", + "E", + "Ề", + "Ế", + "Ệ", + "Ể", + "Ễ", + "Ê", + "I", + "Ì", + "Í", + "Ị", + "Ỉ", + "Ĩ", + "O", + "Ò", + "Ó", + "Ọ", + "Ỏ", + "Õ", + "Ồ", + "Ố", + "Ộ", + "Ổ", + "Ỗ", + "Ô", + "Ờ", + "Ớ", + "Ợ", + "Ở", + "Ỡ", + "Ơ", + "Ù", + "Ú", + "Ụ", + "Ủ", + "Ũ", + "U", + "Ừ", + "Ứ", + "Ự", + "Ử", + "Ữ", + "Ư", + "Ỳ", + "Ý", + "Ỵ", + "Ỷ", + "Ỹ", + "Y", + "Đ", + "B", + "C", + "D", + "F", + "G", + "H", + "I", + "J", + "K", + "L", + "M", + "N", + "P", + "Q", + "R", + "S", + "T", + "V", + "X", + "Y", + "Z", + "W" + ); + // Mảng ko dấu + $marKoDau = array( + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "e", + "e", + "e", + "e", + "e", + "e", + "e", + "e", + "e", + "e", + "e", + "i", + "i", + "i", + "i", + "i", + "o", + "o", + "o", + "o", + "o", + "o", + "o", + "o", + "o", + "o", + "o", + "o", + "o", + "o", + "o", + "o", + "o", + "u", + "u", + "u", + "u", + "u", + "u", + "u", + "u", + "u", + "u", + "u", + "y", + "y", + "y", + "y", + "y", + "d", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "e", + "e", + "e", + "e", + "e", + "e", + "e", + "e", + "e", + "e", + "e", + "e", + "i", + "i", + "i", + "i", + "i", + "i", + "o", + "o", + "o", + "o", + "o", + "o", + "o", + "o", + "o", + "o", + "o", + "o", + "o", + "o", + "o", + "o", + "o", + "o", + "u", + "u", + "u", + "u", + "u", + "u", + "u", + "u", + "u", + "u", + "u", + "u", + "y", + "y", + "y", + "y", + "y", + "y", + "d", + "b", + "c", + "d", + "f", + "g", + "h", + "i", + "j", + "k", + "l", + "m", + "n", + "p", + "q", + "r", + "s", + "t", + "v", + "x", + "y", + "z", + "w" + ); + // Tiến hành chuyển đổi Mảng tiếng Việt thành Mảng ko dấu + // Lọc các ký tự đặc biệt + // Bỏ khoảng trắng + $str = str_replace( + array( + $marTViet, + ',', + ';', + '\'', + '"', + '(', + ')', + '.', + ':', + '…', + '[', + ']', + '|', + '\\', + '?', + "/", + "!", + "@", + "#", + "$", + "^", + "&", + "*", + "+", + "=", + "<", + ">", + "–", + '™', + '®', + '%', + '“', + '”', + '’', + '‘', + ' ' + ), + array( + $marKoDau, + '-', + '-', + '-', + '-', + '-', + '-', + '-', + '-', + '-', + '-', + '-', + '-', + '-', + '-', + '-', + '-', + '-', + '-', + '-', + '-', + '-', + '-', + '-', + '-', + '-', + '-', + '-', + '-', + '-', + '-', + '-', + '-', + '-', + '-', + '-' + ), + $str + ); + // Loại bỏ ký tự trùng lặp special (-) + while (mb_strpos($str, '--') > 0) { + $str = str_replace('--', '-', $str); + } + while (mb_strpos($str, '--') === 0) { + $str = str_replace('--', '-', $str); + } + } - return $str; - } + return $str; + } } -if ( ! function_exists('removeSpecialChar')) { - /** - * Function remove_special_char - Loại bỏ ký tự tiếng Việt theo phong cách phức tạp hơn - * - * @param string $input_string - * - * @return array|string|string[] - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 09/11/2021 10:51 - */ - function removeSpecialChar($input_string = '') - { - if (empty($input_string)) { - return $input_string; - } - $str = trim($input_string); - if ($str) { - $str = str_replace( - array( - '#039', - '!', - '@', - '#', - '$', - '%', - '^', - '&', - '*', - '(', - ')', - '_', - '=', - '{', - '}', - '[', - ']', - '\\', - '/', - '|', - ':', - ';', - '"', - "'", - '=', - "<", - ",", - ">", - ".", - '=', - '?' - ), - '', - $str - ); - } +if (!function_exists('removeSpecialChar')) { + /** + * Function remove_special_char - Loại bỏ ký tự tiếng Việt theo phong cách phức tạp hơn + * + * @param string $input_string + * + * @return array|string|string[] + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 09/11/2021 10:51 + */ + function removeSpecialChar($input_string = '') + { + if (empty($input_string)) { + return $input_string; + } + $str = trim($input_string); + if ($str) { + $str = str_replace( + array( + '#039', + '!', + '@', + '#', + '$', + '%', + '^', + '&', + '*', + '(', + ')', + '_', + '=', + '{', + '}', + '[', + ']', + '\\', + '/', + '|', + ':', + ';', + '"', + "'", + '=', + "<", + ",", + ">", + ".", + '=', + '?' + ), + '', + $str + ); + } - return $str; - } + return $str; + } } -if ( ! function_exists('getPermalinksSEO')) { - /** - * Function getPermalinksSEO - * - * Hàm dùng để convert các ký tự có dấu thành không dấu - * Dùng tốt cho các chức năng SEO - * vì nhiều engine không hiểu được dấu tiếng Việt - * nên cần phải bỏ dấu tiếng Việt đi - * - * @param string $input_string - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 09/11/2021 11:10 - */ - function getPermalinksSEO($input_string = '') - { - if (empty($input_string)) { - return $input_string; - } - $str = $input_string; - if ($str !== '') { - $str = str_replace(array(' ', '---'), '-', boDauTiengViet(trim($str))); - $str = specialCharToNormalChar($str); - $str = convertToLatin($str); - $str = removeSpecialChar($str); - $str = trim(trim(trim($str, '-'), '?'), '!'); - } +if (!function_exists('getPermalinksSEO')) { + /** + * Function getPermalinksSEO + * + * Hàm dùng để convert các ký tự có dấu thành không dấu + * Dùng tốt cho các chức năng SEO + * vì nhiều engine không hiểu được dấu tiếng Việt + * nên cần phải bỏ dấu tiếng Việt đi + * + * @param string $input_string + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 09/11/2021 11:10 + */ + function getPermalinksSEO($input_string = '') + { + if (empty($input_string)) { + return $input_string; + } + $str = $input_string; + if ($str !== '') { + $str = str_replace(array(' ', '---'), '-', boDauTiengViet(trim($str))); + $str = specialCharToNormalChar($str); + $str = convertToLatin($str); + $str = removeSpecialChar($str); + $str = trim(trim(trim($str, '-'), '?'), '!'); + } - return $str; - } + return $str; + } } -if ( ! function_exists('private_url')) { - /** - * Function private_url - * - * @param $uri - * - * @return mixed|string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 16/06/2022 44:55 - */ - function private_url($uri = '') - { - if (function_exists('config_item')) { - return config_item('private_url') . $uri; - } +if (!function_exists('private_url')) { + /** + * Function private_url + * + * @param $uri + * + * @return mixed|string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 16/06/2022 44:55 + */ + function private_url($uri = '') + { + if (function_exists('config_item')) { + return config_item('private_url') . $uri; + } - return $uri; - } + return $uri; + } } -if ( ! function_exists('private_api_url')) { - /** - * Function private_api_url - * - * @param $uri - * - * @return mixed|string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 16/06/2022 44:55 - */ - function private_api_url($uri = '') - { - if (function_exists('config_item')) { - return config_item('private_api_url') . $uri; - } +if (!function_exists('private_api_url')) { + /** + * Function private_api_url + * + * @param $uri + * + * @return mixed|string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 16/06/2022 44:55 + */ + function private_api_url($uri = '') + { + if (function_exists('config_item')) { + return config_item('private_api_url') . $uri; + } - return $uri; - } + return $uri; + } } -if ( ! function_exists('cdn_url')) { - /** - * Function cdn_url - * - * @param $uri - * - * @return mixed|string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 16/06/2022 44:55 - */ - function cdn_url($uri = '') - { - if (function_exists('config_item')) { - return config_item('cdn_url') . $uri; - } +if (!function_exists('cdn_url')) { + /** + * Function cdn_url + * + * @param $uri + * + * @return mixed|string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 16/06/2022 44:55 + */ + function cdn_url($uri = '') + { + if (function_exists('config_item')) { + return config_item('cdn_url') . $uri; + } - return $uri; - } + return $uri; + } } -if ( ! function_exists('images_url')) { - /** - * Function images_url - * - * @param $url - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 10/02/2023 19:42 - */ - function images_url($url = '') - { - $url = trim($url); - $url = bear_framework_image_url($url); - return trim($url); - } +if (!function_exists('images_url')) { + /** + * Function images_url + * + * @param $url + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 10/02/2023 19:42 + */ + function images_url($url = '') + { + $url = trim($url); + $url = bear_framework_image_url($url); + return trim($url); + } } -if ( ! function_exists('audio_url')) { - /** - * Function audio_url - * - * @param $input - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 09/02/2023 01:27 - */ - function audio_url($input = '') - { - $audio_url = trim($input); - if ( ! empty($audio_url)) { - $parse_input = parse_url($audio_url); - if (isset($parse_input['host'])) { - return $audio_url; - } +if (!function_exists('audio_url')) { + /** + * Function audio_url + * + * @param $input + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 09/02/2023 01:27 + */ + function audio_url($input = '') + { + $audio_url = trim($input); + if (!empty($audio_url)) { + $parse_input = parse_url($audio_url); + if (isset($parse_input['host'])) { + return $audio_url; + } - return static_url($audio_url); - } + return static_url($audio_url); + } - return $audio_url; - } + return $audio_url; + } } -if ( ! function_exists('append_params_into_url')) { - /** - * Function Append parameters to URL - * - * @param $url - * @param $params - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 17/04/2023 29:59 - */ - function append_params_into_url($url, $params) - { - $urlParts = parse_url($url); - if (isset($urlParts['query'])) { - $queryParams = array(); - parse_str($urlParts['query'], $queryParams); - $queryParams = array_merge($queryParams, $params); - $urlParts['query'] = http_build_query($queryParams); - } else { - $urlParts['query'] = http_build_query($params); - } +if (!function_exists('append_params_into_url')) { + /** + * Function Append parameters to URL + * + * @param $url + * @param $params + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 17/04/2023 29:59 + */ + function append_params_into_url($url, $params) + { + $urlParts = parse_url($url); + if (isset($urlParts['query'])) { + $queryParams = array(); + parse_str($urlParts['query'], $queryParams); + $queryParams = array_merge($queryParams, $params); + $urlParts['query'] = http_build_query($queryParams); + } else { + $urlParts['query'] = http_build_query($params); + } - $newUrl = $urlParts['scheme'] . '://' . $urlParts['host'] . $urlParts['path'] . '?' . $urlParts['query']; + $newUrl = $urlParts['scheme'] . '://' . $urlParts['host'] . $urlParts['path'] . '?' . $urlParts['query']; - if (isset($urlParts['port'])) { - $newUrl = $urlParts['scheme'] . '://' . $urlParts['host'] . ':' . $urlParts['port'] . $urlParts['path'] . '?' . $urlParts['query']; - } + if (isset($urlParts['port'])) { + $newUrl = $urlParts['scheme'] . '://' . $urlParts['host'] . ':' . $urlParts['port'] . $urlParts['path'] . '?' . $urlParts['query']; + } - return $newUrl; - } + return $newUrl; + } } -if ( ! function_exists('append_query_string_to_current_url')) { - /** - * Function Get current URL including query string - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 17/04/2023 31:27 - */ - function append_query_string_to_current_url() - { - if (function_exists('current_url')) { - $url = current_url(); - if ( ! empty($_SERVER['QUERY_STRING'])) { - $url .= '?' . $_SERVER['QUERY_STRING']; - } +if (!function_exists('append_query_string_to_current_url')) { + /** + * Function Get current URL including query string + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 17/04/2023 31:27 + */ + function append_query_string_to_current_url() + { + if (function_exists('current_url')) { + $url = current_url(); + if (!empty($_SERVER['QUERY_STRING'])) { + $url .= '?' . $_SERVER['QUERY_STRING']; + } - return $url; - } + return $url; + } - return ''; - } + return ''; + } } diff --git a/helpers/uuid_helper.php b/helpers/uuid_helper.php index db1ceb4..5b1d40c 100644 --- a/helpers/uuid_helper.php +++ b/helpers/uuid_helper.php @@ -8,131 +8,131 @@ * Date: 09/11/2021 * Time: 08:52 */ -if ( ! function_exists('uuid_is_valid')) { - /** - * @param $uuid - * - * @return bool - */ - function uuid_is_valid($uuid) - { - return preg_match( - '/^\{?[0-9a-f]{8}\-?[0-9a-f]{4}\-?[0-9a-f]{4}\-?' . '[0-9a-f]{4}\-?[0-9a-f]{12}\}?$/i', - $uuid - ) === 1; - } +if (!function_exists('uuid_is_valid')) { + /** + * @param $uuid + * + * @return bool + */ + function uuid_is_valid($uuid) + { + return preg_match( + '/^\{?[0-9a-f]{8}\-?[0-9a-f]{4}\-?[0-9a-f]{4}\-?' . '[0-9a-f]{4}\-?[0-9a-f]{12}\}?$/i', + $uuid + ) === 1; + } } -if ( ! function_exists('generate_uuid_v3')) { - /** - * Generate v3 UUID - * - * @param $namespace - * @param $name - * - * @return bool|string - */ - function generate_uuid_v3($namespace, $name) - { - if ( ! uuid_is_valid($namespace)) { - return false; - } - // Get hexadecimal components of namespace - $nhex = str_replace(array('-', '{', '}'), '', $namespace); - // Binary Value - $nstr = ''; - // Convert Namespace UUID to bits - $iMax = mb_strlen($nhex); - for ($i = 0; $i < $iMax; $i += 2) { - $nstr .= mb_chr(hexdec($nhex[$i] . $nhex[$i + 1])); - } - // Calculate hash value - $hash = md5($nstr . $name); +if (!function_exists('generate_uuid_v3')) { + /** + * Generate v3 UUID + * + * @param $namespace + * @param $name + * + * @return bool|string + */ + function generate_uuid_v3($namespace, $name) + { + if (!uuid_is_valid($namespace)) { + return false; + } + // Get hexadecimal components of namespace + $nhex = str_replace(array('-', '{', '}'), '', $namespace); + // Binary Value + $nstr = ''; + // Convert Namespace UUID to bits + $iMax = mb_strlen($nhex); + for ($i = 0; $i < $iMax; $i += 2) { + $nstr .= mb_chr(hexdec($nhex[$i] . $nhex[$i + 1])); + } + // Calculate hash value + $hash = md5($nstr . $name); - return sprintf( - '%08s-%04s-%04x-%04x-%12s', // 32 bits for "time_low" - mb_substr($hash, 0, 8), // 16 bits for "time_mid" - mb_substr($hash, 8, 4), // 16 bits for "time_hi_and_version", + return sprintf( + '%08s-%04s-%04x-%04x-%12s', // 32 bits for "time_low" + mb_substr($hash, 0, 8), // 16 bits for "time_mid" + mb_substr($hash, 8, 4), // 16 bits for "time_hi_and_version", - // four most significant bits holds version number 3 - (hexdec(mb_substr($hash, 12, 4)) & 0x0fff) | 0x3000, // 16 bits, 8 bits for "clk_seq_hi_res", + // four most significant bits holds version number 3 + (hexdec(mb_substr($hash, 12, 4)) & 0x0fff) | 0x3000, // 16 bits, 8 bits for "clk_seq_hi_res", - // 8 bits for "clk_seq_low", + // 8 bits for "clk_seq_low", - // two most significant bits holds zero and one for variant DCE1.1 - (hexdec(mb_substr($hash, 16, 4)) & 0x3fff) | 0x8000, // 48 bits for "node" - mb_substr($hash, 20, 12) - ); - } + // two most significant bits holds zero and one for variant DCE1.1 + (hexdec(mb_substr($hash, 16, 4)) & 0x3fff) | 0x8000, // 48 bits for "node" + mb_substr($hash, 20, 12) + ); + } } -if ( ! function_exists('generate_uuid_v4')) { - /** - * Function generate_uuid_v4 - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 09/11/2021 52:37 - */ - function generate_uuid_v4() - { - return sprintf( - '%04x%04x-%04x-%04x-%04x-%04x%04x%04x', - mt_rand(0, 0xffff), // 32 bits for "time_low" - mt_rand(0, 0xffff), // 16 bits for "time_mid" - mt_rand(0, 0xffff), // 16 bits for "time_hi_and_version", +if (!function_exists('generate_uuid_v4')) { + /** + * Function generate_uuid_v4 + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 09/11/2021 52:37 + */ + function generate_uuid_v4() + { + return sprintf( + '%04x%04x-%04x-%04x-%04x-%04x%04x%04x', + mt_rand(0, 0xffff), // 32 bits for "time_low" + mt_rand(0, 0xffff), // 16 bits for "time_mid" + mt_rand(0, 0xffff), // 16 bits for "time_hi_and_version", - // four most significant bits holds version number 4 - mt_rand(0, 0x0fff) | 0x4000, // 16 bits, 8 bits for "clk_seq_hi_res", + // four most significant bits holds version number 4 + mt_rand(0, 0x0fff) | 0x4000, // 16 bits, 8 bits for "clk_seq_hi_res", - // 8 bits for "clk_seq_low", + // 8 bits for "clk_seq_low", - // two most significant bits holds zero and one for variant DCE1.1 - mt_rand(0, 0x3fff) | 0x8000, // 48 bits for "node" - mt_rand(0, 0xffff), - mt_rand(0, 0xffff), - mt_rand(0, 0xffff) - ); - } + // two most significant bits holds zero and one for variant DCE1.1 + mt_rand(0, 0x3fff) | 0x8000, // 48 bits for "node" + mt_rand(0, 0xffff), + mt_rand(0, 0xffff), + mt_rand(0, 0xffff) + ); + } } -if ( ! function_exists('generate_uuid_v5')) { - /** - * Generate v5 UUID - * - * @param $namespace - * @param $name - * - * @return bool|string - */ - function generate_uuid_v5($namespace, $name) - { - if ( ! uuid_is_valid($namespace)) { - return false; - } - // Get hexadecimal components of namespace - $nhex = str_replace(array('-', '{', '}'), '', $namespace); - // Binary Value - $nstr = ''; - // Convert Namespace UUID to bits - $iMax = mb_strlen($nhex); - for ($i = 0; $i < $iMax; $i += 2) { - $nstr .= mb_chr(hexdec($nhex[$i] . $nhex[$i + 1])); - } - // Calculate hash value - $hash = sha1($nstr . $name); +if (!function_exists('generate_uuid_v5')) { + /** + * Generate v5 UUID + * + * @param $namespace + * @param $name + * + * @return bool|string + */ + function generate_uuid_v5($namespace, $name) + { + if (!uuid_is_valid($namespace)) { + return false; + } + // Get hexadecimal components of namespace + $nhex = str_replace(array('-', '{', '}'), '', $namespace); + // Binary Value + $nstr = ''; + // Convert Namespace UUID to bits + $iMax = mb_strlen($nhex); + for ($i = 0; $i < $iMax; $i += 2) { + $nstr .= mb_chr(hexdec($nhex[$i] . $nhex[$i + 1])); + } + // Calculate hash value + $hash = sha1($nstr . $name); - return sprintf( - '%08s-%04s-%04x-%04x-%12s', // 32 bits for "time_low" - mb_substr($hash, 0, 8), // 16 bits for "time_mid" - mb_substr($hash, 8, 4), // 16 bits for "time_hi_and_version", + return sprintf( + '%08s-%04s-%04x-%04x-%12s', // 32 bits for "time_low" + mb_substr($hash, 0, 8), // 16 bits for "time_mid" + mb_substr($hash, 8, 4), // 16 bits for "time_hi_and_version", - // four most significant bits holds version number 5 - (hexdec(mb_substr($hash, 12, 4)) & 0x0fff) | 0x5000, // 16 bits, 8 bits for "clk_seq_hi_res", + // four most significant bits holds version number 5 + (hexdec(mb_substr($hash, 12, 4)) & 0x0fff) | 0x5000, // 16 bits, 8 bits for "clk_seq_hi_res", - // 8 bits for "clk_seq_low", + // 8 bits for "clk_seq_low", - // two most significant bits holds zero and one for variant DCE1.1 - (hexdec(mb_substr($hash, 16, 4)) & 0x3fff) | 0x8000, // 48 bits for "node" - mb_substr($hash, 20, 12) - ); - } + // two most significant bits holds zero and one for variant DCE1.1 + (hexdec(mb_substr($hash, 16, 4)) & 0x3fff) | 0x8000, // 48 bits for "node" + mb_substr($hash, 20, 12) + ); + } } diff --git a/helpers/video_embed_helper.php b/helpers/video_embed_helper.php index 51dcc2f..e0d8a29 100644 --- a/helpers/video_embed_helper.php +++ b/helpers/video_embed_helper.php @@ -8,110 +8,110 @@ * Date: 12/02/2023 * Time: 23:16 */ -if ( ! function_exists('convert_video_embed_vimeo')) { - function convert_video_embed_vimeo($vimeo) - { - if (empty($vimeo)) { - return $vimeo; - } - $vimeo = str_replace( - array( - 'https://vimeo.com/', - 'http://vimeo.com/' - ), - '//player.vimeo.com/video/', - $vimeo - ); +if (!function_exists('convert_video_embed_vimeo')) { + function convert_video_embed_vimeo($vimeo) + { + if (empty($vimeo)) { + return $vimeo; + } + $vimeo = str_replace( + array( + 'https://vimeo.com/', + 'http://vimeo.com/' + ), + '//player.vimeo.com/video/', + $vimeo + ); - return trim($vimeo); - } + return trim($vimeo); + } } -if ( ! function_exists('convert_video_embed_dailymotion')) { - function convert_video_embed_dailymotion($dailymotion) - { - if (empty($dailymotion)) { - return $dailymotion; - } - $dailymotion = str_replace( - array( - 'https://www.dailymotion.com/video/', - 'http://www.dailymotion.com/video/' - ), - '//www.dailymotion.com/embed/video/', - $dailymotion - ); +if (!function_exists('convert_video_embed_dailymotion')) { + function convert_video_embed_dailymotion($dailymotion) + { + if (empty($dailymotion)) { + return $dailymotion; + } + $dailymotion = str_replace( + array( + 'https://www.dailymotion.com/video/', + 'http://www.dailymotion.com/video/' + ), + '//www.dailymotion.com/embed/video/', + $dailymotion + ); - return trim($dailymotion); - } + return trim($dailymotion); + } } -if ( ! function_exists('convert_video_v_embed_youtube')) { - function convert_video_v_embed_youtube($youtube) - { - if (empty($youtube)) { - return $youtube; - } - $youtube = str_replace( - array( - 'https://www.youtube.com/watch?v=', - 'http://www.youtube.com/watch?v=', - 'https://www.youtube.com/embed/', - 'http://www.youtube.com/embed/' - ), - '//www.youtube.com/v/', - $youtube - ); +if (!function_exists('convert_video_v_embed_youtube')) { + function convert_video_v_embed_youtube($youtube) + { + if (empty($youtube)) { + return $youtube; + } + $youtube = str_replace( + array( + 'https://www.youtube.com/watch?v=', + 'http://www.youtube.com/watch?v=', + 'https://www.youtube.com/embed/', + 'http://www.youtube.com/embed/' + ), + '//www.youtube.com/v/', + $youtube + ); - return trim($youtube); - } + return trim($youtube); + } } -if ( ! function_exists('convert_video_embed_youtube')) { - function convert_video_embed_youtube($youtube) - { - if (empty($youtube)) { - return $youtube; - } - $youtube = str_replace( - array( - 'https://www.youtube.com/watch?v=', - 'http://www.youtube.com/watch?v=', - 'https://www.youtube.com/v/', - 'http://www.youtube.com/v/' - ), - '//www.youtube.com/embed/', - $youtube - ); +if (!function_exists('convert_video_embed_youtube')) { + function convert_video_embed_youtube($youtube) + { + if (empty($youtube)) { + return $youtube; + } + $youtube = str_replace( + array( + 'https://www.youtube.com/watch?v=', + 'http://www.youtube.com/watch?v=', + 'https://www.youtube.com/v/', + 'http://www.youtube.com/v/' + ), + '//www.youtube.com/embed/', + $youtube + ); - return trim($youtube); - } + return trim($youtube); + } } -if ( ! function_exists('clean_youtube_allow_fullscreen')) { - function clean_youtube_allow_fullscreen($youtube) - { - if (empty($youtube)) { - return $youtube; - } - if ($youtube !== '') { - $youtube = str_replace( - array( - 'allowfullscreen="undefined"', - 'allowfullscreen="yes"', - 'allowfullscreen="true"' - ), - 'allowfullscreen', - $youtube - ); - } +if (!function_exists('clean_youtube_allow_fullscreen')) { + function clean_youtube_allow_fullscreen($youtube) + { + if (empty($youtube)) { + return $youtube; + } + if ($youtube !== '') { + $youtube = str_replace( + array( + 'allowfullscreen="undefined"', + 'allowfullscreen="yes"', + 'allowfullscreen="true"' + ), + 'allowfullscreen', + $youtube + ); + } - return $youtube; - } + return $youtube; + } } -if ( ! function_exists('youtube_image_thumbnail')) { - function youtube_image_thumbnail($id, $filename = 'hqdefault.jpg') - { - if (empty($id)) { - return $id; - } +if (!function_exists('youtube_image_thumbnail')) { + function youtube_image_thumbnail($id, $filename = 'hqdefault.jpg') + { + if (empty($id)) { + return $id; + } - return 'https://i.ytimg.com/vi/' . trim($id) . '/' . trim($filename); - } + return 'https://i.ytimg.com/vi/' . trim($id) . '/' . trim($filename); + } } diff --git a/helpers/vn_province_helper.php b/helpers/vn_province_helper.php index 09d70f2..83862a0 100644 --- a/helpers/vn_province_helper.php +++ b/helpers/vn_province_helper.php @@ -8,75 +8,75 @@ * Date: 16/06/2022 * Time: 10:12 */ -if ( ! function_exists('check_vn_province_code')) { - /** - * Function check_vn_province_code - * - * @param string $code - * - * @return bool|string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 22/08/2022 10:07 - */ - function check_vn_province_code($code = "") - { - $arr = array( - 'MB' => 'Miền Bắc', - 'MT' => 'Miền Trung', - 'MN' => 'Miền Nam', - 'AG' => 'An Giang', - 'VT' => 'Bà Rịa - Vũng Tàu', - 'BG' => 'Bắc Giang', - 'BK' => 'Bắc Cạn', - 'BL' => 'Bạc Liêu', - 'BTH' => 'Bình Thuận', - 'BT' => 'Bến Tre', - 'BDG' => 'Bình Dương', - 'BD' => 'Bình Định', - 'BP' => 'Bình Phước', - 'CM' => 'Cà Mau', - 'DL' => 'Đắc lắk', - 'Dak Nong' => 'Đắk Nông', - 'DAKNONG' => 'Đắk Nông', - 'DN' => 'Đà Nẵng', - 'DT' => 'Đồng Tháp', - 'GL' => 'Gia Lai', - 'HN' => 'Miền Bắc', - 'HT' => 'Hà Tĩnh', - 'HG' => 'Hậu Giang', - 'KH' => 'Khánh Hòa', - 'KG' => 'Kiên Giang', - 'KT' => 'Kon Tum', - 'LD' => 'Lâm Đồng', - 'VL' => 'Vĩnh Long', - 'L' => 'Long An', - 'NA' => 'Nghệ An', - 'NT' => 'Ninh Thuận', - 'QB' => 'Quảng Bình', - 'QNG' => 'Quảng Ngãi', - 'QN' => 'Quảng Nam', - 'QT' => 'Quảng Trị', - 'ST' => 'Sóc Trăng', - 'TN' => 'Tây Ninh', - 'TG' => 'Tiền Giang', - 'TV' => 'Trà Vinh', - 'PY' => 'Phú Yên', - 'CT' => 'Cần Thơ', - 'DNA' => 'Đồng Nai', - 'HCM' => 'Hồ Chí Minh', - 'TP' => 'Hồ Chí Minh', - 'DNO' => 'Đắc Nông', - 'LA' => 'Long An', - 'H' => 'Thừa Thiên Huế', - 'TTH' => 'Thừa Thiên Huế', - 'HUE' => 'Thừa Thiên Huế' - ); +if (!function_exists('check_vn_province_code')) { + /** + * Function check_vn_province_code + * + * @param string $code + * + * @return bool|string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 22/08/2022 10:07 + */ + function check_vn_province_code($code = "") + { + $arr = array( + 'MB' => 'Miền Bắc', + 'MT' => 'Miền Trung', + 'MN' => 'Miền Nam', + 'AG' => 'An Giang', + 'VT' => 'Bà Rịa - Vũng Tàu', + 'BG' => 'Bắc Giang', + 'BK' => 'Bắc Cạn', + 'BL' => 'Bạc Liêu', + 'BTH' => 'Bình Thuận', + 'BT' => 'Bến Tre', + 'BDG' => 'Bình Dương', + 'BD' => 'Bình Định', + 'BP' => 'Bình Phước', + 'CM' => 'Cà Mau', + 'DL' => 'Đắc lắk', + 'Dak Nong' => 'Đắk Nông', + 'DAKNONG' => 'Đắk Nông', + 'DN' => 'Đà Nẵng', + 'DT' => 'Đồng Tháp', + 'GL' => 'Gia Lai', + 'HN' => 'Miền Bắc', + 'HT' => 'Hà Tĩnh', + 'HG' => 'Hậu Giang', + 'KH' => 'Khánh Hòa', + 'KG' => 'Kiên Giang', + 'KT' => 'Kon Tum', + 'LD' => 'Lâm Đồng', + 'VL' => 'Vĩnh Long', + 'L' => 'Long An', + 'NA' => 'Nghệ An', + 'NT' => 'Ninh Thuận', + 'QB' => 'Quảng Bình', + 'QNG' => 'Quảng Ngãi', + 'QN' => 'Quảng Nam', + 'QT' => 'Quảng Trị', + 'ST' => 'Sóc Trăng', + 'TN' => 'Tây Ninh', + 'TG' => 'Tiền Giang', + 'TV' => 'Trà Vinh', + 'PY' => 'Phú Yên', + 'CT' => 'Cần Thơ', + 'DNA' => 'Đồng Nai', + 'HCM' => 'Hồ Chí Minh', + 'TP' => 'Hồ Chí Minh', + 'DNO' => 'Đắc Nông', + 'LA' => 'Long An', + 'H' => 'Thừa Thiên Huế', + 'TTH' => 'Thừa Thiên Huế', + 'HUE' => 'Thừa Thiên Huế' + ); - if (isset($arr[$code])) { - return $arr[$code]; - } + if (isset($arr[$code])) { + return $arr[$code]; + } - return false; - } + return false; + } } diff --git a/helpers/xml_helper.php b/helpers/xml_helper.php index 46d67ef..ffbc79b 100644 --- a/helpers/xml_helper.php +++ b/helpers/xml_helper.php @@ -8,187 +8,187 @@ * Date: 09/11/2021 * Time: 08:55 */ -if ( ! function_exists('parse_sitemap_index')) { - /** - * Function parse_sitemap_index - * - * @param string|array $loc - * @param string $lastmod - * @param string $type - * @param string $newline - * - * @return string|null - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 09/11/2021 57:45 - */ - function parse_sitemap_index($loc = '', $lastmod = '', $type = 'property', $newline = "\n") - { - if (function_exists('base_url')) { - // Since we allow the data to be passes as a string, a simple array - // or a multidimensional one, we need to do a little prepping. - if ( ! is_array($loc)) { - $loc = array( - array( - 'loc' => $loc, - 'lastmod' => $lastmod, - 'type' => $type, - 'newline' => $newline - ) - ); - } elseif (isset($loc['loc'])) { - // Turn single array into multidimensional - $loc = array($loc); - } - $str = ''; - foreach ($loc as $meta) { - $type = 'loc'; - $loc = isset($meta['loc']) ? $meta['loc'] : ''; - $lastmod = isset($meta['lastmod']) ? $meta['lastmod'] : ''; - $newline = isset($meta['newline']) ? $meta['newline'] : "\n"; - $str .= "\n\n"; - $str .= '<' . $type . '>' . base_url($loc . '.xml') . ''; - $str .= "\n" . $lastmod . ""; - $str .= "\n"; - $str .= $newline; - } +if (!function_exists('parse_sitemap_index')) { + /** + * Function parse_sitemap_index + * + * @param string|array $loc + * @param string $lastmod + * @param string $type + * @param string $newline + * + * @return string|null + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 09/11/2021 57:45 + */ + function parse_sitemap_index($loc = '', $lastmod = '', $type = 'property', $newline = "\n") + { + if (function_exists('base_url')) { + // Since we allow the data to be passes as a string, a simple array + // or a multidimensional one, we need to do a little prepping. + if (!is_array($loc)) { + $loc = array( + array( + 'loc' => $loc, + 'lastmod' => $lastmod, + 'type' => $type, + 'newline' => $newline + ) + ); + } elseif (isset($loc['loc'])) { + // Turn single array into multidimensional + $loc = array($loc); + } + $str = ''; + foreach ($loc as $meta) { + $type = 'loc'; + $loc = isset($meta['loc']) ? $meta['loc'] : ''; + $lastmod = isset($meta['lastmod']) ? $meta['lastmod'] : ''; + $newline = isset($meta['newline']) ? $meta['newline'] : "\n"; + $str .= "\n\n"; + $str .= '<' . $type . '>' . base_url($loc . '.xml') . ''; + $str .= "\n" . $lastmod . ""; + $str .= "\n"; + $str .= $newline; + } - return $str; - } + return $str; + } - return null; - } + return null; + } } -if ( ! function_exists('parse_sitemap')) { - /** - * Function parse_sitemap - * - * @param string|array $domain - * @param string|array $loc - * @param string $lastmod - * @param string $type - * @param string $newline - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 09/21/2021 13:07 - */ - function parse_sitemap($domain = '', $loc = '', $lastmod = '', $type = 'property', $newline = "\n") - { - // Since we allow the data to be passes as a string, a simple array - // or a multidimensional one, we need to do a little prepping. - if ( ! is_array($loc)) { - $loc = array( - array( - 'loc' => $loc, - 'lastmod' => $lastmod, - 'type' => $type, - 'newline' => $newline - ) - ); - } elseif (isset($loc['loc'])) { - // Turn single array into multidimensional - $loc = array($loc); - } - $str = ''; - foreach ($loc as $meta) { - $type = 'loc'; - $loc = isset($meta['loc']) ? $meta['loc'] : ''; - $lastmod = isset($meta['lastmod']) ? $meta['lastmod'] : ''; - $newline = isset($meta['newline']) ? $meta['newline'] : "\n"; - $str .= "\n\n"; - $str .= '<' . $type . '>' . trim($domain) . trim($loc) . '.xml' . ''; - $str .= "\n" . $lastmod . ""; - $str .= "\n"; - $str .= $newline; - } +if (!function_exists('parse_sitemap')) { + /** + * Function parse_sitemap + * + * @param string|array $domain + * @param string|array $loc + * @param string $lastmod + * @param string $type + * @param string $newline + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 09/21/2021 13:07 + */ + function parse_sitemap($domain = '', $loc = '', $lastmod = '', $type = 'property', $newline = "\n") + { + // Since we allow the data to be passes as a string, a simple array + // or a multidimensional one, we need to do a little prepping. + if (!is_array($loc)) { + $loc = array( + array( + 'loc' => $loc, + 'lastmod' => $lastmod, + 'type' => $type, + 'newline' => $newline + ) + ); + } elseif (isset($loc['loc'])) { + // Turn single array into multidimensional + $loc = array($loc); + } + $str = ''; + foreach ($loc as $meta) { + $type = 'loc'; + $loc = isset($meta['loc']) ? $meta['loc'] : ''; + $lastmod = isset($meta['lastmod']) ? $meta['lastmod'] : ''; + $newline = isset($meta['newline']) ? $meta['newline'] : "\n"; + $str .= "\n\n"; + $str .= '<' . $type . '>' . trim($domain) . trim($loc) . '.xml' . ''; + $str .= "\n" . $lastmod . ""; + $str .= "\n"; + $str .= $newline; + } - return $str; - } + return $str; + } } -if ( ! function_exists('xml_convert')) { - /** - * Function xml_convert - Convert Reserved XML characters to Entities - * - * @param $str - * @param $protect_all - * - * @return array|string|string[]|null - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 09/02/2023 20:16 - */ - function xml_convert($str, $protect_all = false) - { - $temp = '__TEMP_AMPERSANDS__'; +if (!function_exists('xml_convert')) { + /** + * Function xml_convert - Convert Reserved XML characters to Entities + * + * @param $str + * @param $protect_all + * + * @return array|string|string[]|null + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 09/02/2023 20:16 + */ + function xml_convert($str, $protect_all = false) + { + $temp = '__TEMP_AMPERSANDS__'; - // Replace entities to temporary markers so that - // ampersands won't get messed up - $str = preg_replace('/&#(\d+);/', $temp . '\\1;', $str); + // Replace entities to temporary markers so that + // ampersands won't get messed up + $str = preg_replace('/&#(\d+);/', $temp . '\\1;', $str); - if ($protect_all === true) { - $str = preg_replace('/&(\w+);/', $temp . '\\1;', $str); - } + if ($protect_all === true) { + $str = preg_replace('/&(\w+);/', $temp . '\\1;', $str); + } - $str = str_replace(array('&', '<', '>', '"', "'", '-'), - array('&', '<', '>', '"', ''', '-'), - $str); + $str = str_replace(array('&', '<', '>', '"', "'", '-'), + array('&', '<', '>', '"', ''', '-'), + $str); - // Decode the temp markers back to entities - $str = preg_replace('/' . $temp . '(\d+);/', '&#\\1;', $str); + // Decode the temp markers back to entities + $str = preg_replace('/' . $temp . '(\d+);/', '&#\\1;', $str); - if ($protect_all === true) { - return preg_replace('/' . $temp . '(\w+);/', '&\\1;', $str); - } + if ($protect_all === true) { + return preg_replace('/' . $temp . '(\w+);/', '&\\1;', $str); + } - return $str; - } + return $str; + } } -if ( ! function_exists('xml_get_value')) { - /** - * Function xml_get_value - * - * @param $xml - * @param $openTag - * @param $closeTag - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 07/08/2023 41:49 - */ - function xml_get_value($xml, $openTag, $closeTag) - { - $f = mb_strpos($xml, $openTag) + mb_strlen($openTag); - $l = mb_strpos($xml, $closeTag); +if (!function_exists('xml_get_value')) { + /** + * Function xml_get_value + * + * @param $xml + * @param $openTag + * @param $closeTag + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 07/08/2023 41:49 + */ + function xml_get_value($xml, $openTag, $closeTag) + { + $f = mb_strpos($xml, $openTag) + mb_strlen($openTag); + $l = mb_strpos($xml, $closeTag); - return ($f <= $l) ? mb_substr($xml, $f, $l - $f) : ""; - } + return ($f <= $l) ? mb_substr($xml, $f, $l - $f) : ""; + } } -if ( ! function_exists('xml_to_json')) { - /** - * Function xml_to_json - * - * Convert XML string to JSON - * - * @param $fileContents - * - * @return false|string|null - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 24/02/2023 26:27 - */ - function xml_to_json($fileContents) - { - if (empty($fileContents)) { - return null; - } +if (!function_exists('xml_to_json')) { + /** + * Function xml_to_json + * + * Convert XML string to JSON + * + * @param $fileContents + * + * @return false|string|null + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 24/02/2023 26:27 + */ + function xml_to_json($fileContents) + { + if (empty($fileContents)) { + return null; + } - $fileContents = str_replace(array("\n", "\r", "\t"), '', $fileContents); - $fileContents = trim(str_replace('"', "'", $fileContents)); - $simpleXml = simplexml_load_string($fileContents); + $fileContents = str_replace(array("\n", "\r", "\t"), '', $fileContents); + $fileContents = trim(str_replace('"', "'", $fileContents)); + $simpleXml = simplexml_load_string($fileContents); - return json_encode($simpleXml); - } + return json_encode($simpleXml); + } } diff --git a/src/BaseHelper.php b/src/BaseHelper.php index 73660e6..5c87bc7 100644 --- a/src/BaseHelper.php +++ b/src/BaseHelper.php @@ -19,56 +19,56 @@ */ class BaseHelper { - const VERSION = '1.6.2'; - const LAST_MODIFIED = '2024-04-06'; - const PROJECT_NAME = 'CodeIgniter - Basic Helper'; - const AUTHOR_NAME = 'Hung Nguyen'; - const AUTHOR_FULL_NAME = 'Hung Nguyen'; - const AUTHOR_EMAIL = 'dev@nguyenanhung.com'; - const AUTHOR_WEB = 'https://nguyenanhung.com'; - const AUTHOR_BLOG = 'https://blog.nguyenanhung.com'; - const GITHUB_URL = 'https://github.com/nguyenanhung/codeigniter-basic-helper'; - const GITHUB_ISSUES_URL = 'https://github.com/nguyenanhung/codeigniter-basic-helper/issues'; - const PACKAGES_URL = 'https://packagist.org/packages/nguyenanhung/codeigniter-basic-helper'; + const VERSION = '1.6.3'; + const LAST_MODIFIED = '2024-04-12'; + const PROJECT_NAME = 'CodeIgniter - Basic Helper'; + const AUTHOR_NAME = 'Hung Nguyen'; + const AUTHOR_FULL_NAME = 'Hung Nguyen'; + const AUTHOR_EMAIL = 'dev@nguyenanhung.com'; + const AUTHOR_WEB = 'https://nguyenanhung.com'; + const AUTHOR_BLOG = 'https://blog.nguyenanhung.com'; + const GITHUB_URL = 'https://github.com/nguyenanhung/codeigniter-basic-helper'; + const GITHUB_ISSUES_URL = 'https://github.com/nguyenanhung/codeigniter-basic-helper/issues'; + const PACKAGES_URL = 'https://packagist.org/packages/nguyenanhung/codeigniter-basic-helper'; - public function getVersion() - { - return self::VERSION; - } + public function getVersion() + { + return self::VERSION; + } - public static function version() - { - return self::VERSION; - } + public static function version() + { + return self::VERSION; + } - public function getAuthor() - { - return array( - 'name' => self::AUTHOR_NAME, - 'full_name' => self::AUTHOR_FULL_NAME, - 'email' => self::AUTHOR_EMAIL, - 'web' => self::AUTHOR_WEB, - 'blog' => self::AUTHOR_BLOG - ); - } + public function getAuthor() + { + return array( + 'name' => self::AUTHOR_NAME, + 'full_name' => self::AUTHOR_FULL_NAME, + 'email' => self::AUTHOR_EMAIL, + 'web' => self::AUTHOR_WEB, + 'blog' => self::AUTHOR_BLOG + ); + } - public function getPackageInfo() - { - return array( - 'project_name' => self::PROJECT_NAME, - 'project_version' => self::VERSION, - 'version_updated' => self::LAST_MODIFIED, - 'project_github' => self::GITHUB_URL, - 'project_packages' => self::PACKAGES_URL, - 'project_maintainer' => $this->getAuthor() - ); - } + public function getPackageInfo() + { + return array( + 'project_name' => self::PROJECT_NAME, + 'project_version' => self::VERSION, + 'version_updated' => self::LAST_MODIFIED, + 'project_github' => self::GITHUB_URL, + 'project_packages' => self::PACKAGES_URL, + 'project_maintainer' => $this->getAuthor() + ); + } - public static function writeLn($message, $newLine = "\n") - { - if (function_exists('json_encode') && (is_array($message) || is_object($message))) { - $message = json_encode($message); - } - echo $message . $newLine; - } + public static function writeLn($message, $newLine = "\n") + { + if (function_exists('json_encode') && (is_array($message) || is_object($message))) { + $message = json_encode($message); + } + echo $message . $newLine; + } } diff --git a/src/BasicCurl.php b/src/BasicCurl.php index 66e7f24..fafd59b 100644 --- a/src/BasicCurl.php +++ b/src/BasicCurl.php @@ -41,823 +41,823 @@ */ final class BasicCurl extends BaseHelper { - // The HTTP authentication method(s) to use. - - /** - * @var int Type AUTH_BASIC - */ - const AUTH_BASIC = CURLAUTH_BASIC; - - /** - * @var int Type AUTH_DIGEST - */ - const AUTH_DIGEST = CURLAUTH_DIGEST; - - /** - * @var int Type AUTH_GSSNEGOTIATE - */ - const AUTH_GSSNEGOTIATE = CURLAUTH_GSSNEGOTIATE; - - /** - * @var int Type AUTH_NTLM - */ - const AUTH_NTLM = CURLAUTH_NTLM; - - /** - * @var int Type AUTH_ANY - */ - const AUTH_ANY = CURLAUTH_ANY; - - /** - * @var int Type AUTH_ANYSAFE - */ - const AUTH_ANYSAFE = CURLAUTH_ANYSAFE; - - /** - * @var string The user agent name which is set when making a request - */ - const USER_AGENT = 'PHP Curl/2.6 (+https://github.com/nguyenanhung/codeigniter-basic-helper)'; - - private $_cookies = array(); - - private $_headers = array(); - - /** - * @var resource Contains the curl resource created by `curl_init()` function - */ - public $curl; - - /** - * @var bool Whether an error occurred or not - */ - public $error = false; - - /** - * @var int Contains the error code of the current request, 0 means no error happened - */ - public $error_code = 0; - - /** - * @var string If the curl request failed, the error message is contained - */ - public $error_message = null; - - /** - * @var bool Whether an error occurred or not - */ - public $curl_error = false; - - /** - * @var int Contains the error code of the current request, 0 means no error happened. - * @see https://curl.haxx.se/libcurl/c/libcurl-errors.html - */ - public $curl_error_code = 0; - - /** - * @var string If the curl request failed, the error message is contained - */ - public $curl_error_message = null; - - /** - * @var bool Whether an error occurred or not - */ - public $http_error = false; - - /** - * @var int Contains the status code of the current processed request. - */ - public $http_status_code = 0; - - /** - * @var string If the curl request failed, the error message is contained - */ - public $http_error_message = null; - - /** - * @var string|array TBD (ensure type) Contains the request header information - */ - public $request_headers = null; - - /** - * @var string|array TBD (ensure type) Contains the response header information - */ - public $response_headers = array(); - - /** - * @var string|false|null Contains the response from the curl request - */ - public $response = null; - - /** - * @var bool Whether the current section of response headers is after 'HTTP/1.1 100 Continue' - */ - protected $response_header_continue = false; - - /** - * Constructor ensures the available curl extension is loaded. - * - * @throws \RuntimeException - */ - public function __construct() - { - if ( ! extension_loaded('curl')) { - throw new \RuntimeException( - 'The cURL extensions is not loaded, make sure you have installed the cURL extension: https://php.net/manual/curl.setup.php' - ); - } - - $this->init(); - } - - // private methods - - /** - * Initializer for the curl resource. - * - * Is called by the __construct() of the class or when the curl request is reset. - * - * @return self - */ - private function init() - { - $this->curl = curl_init(); - $this->setUserAgent(self::USER_AGENT); - $this->setOpt(CURLINFO_HEADER_OUT, true); - $this->setOpt(CURLOPT_HEADER, false); - $this->setOpt(CURLOPT_RETURNTRANSFER, true); - - return $this; - } - - /** - * Handle writing the response headers - * - * @param resource $curl The current curl resource - * @param string $header_line A line from the list of response headers - * - * @return int Returns the length of the $header_line - */ - public function addResponseHeaderLine($curl, $header_line) - { - $trimmed_header = trim($header_line, "\r\n"); - - if ($trimmed_header === "") { - $this->response_header_continue = false; - } elseif (strtolower($trimmed_header) === 'http/1.1 100 continue') { - $this->response_header_continue = true; - } elseif ( ! $this->response_header_continue) { - $this->response_headers[] = $trimmed_header; - } - - return strlen($header_line); - } - - // protected methods - - /** - * Execute the curl request based on the respective settings. - * - * @return int Returns the error code for the current curl request - */ - public function exec() - { - $this->setOpt(CURLOPT_HEADERFUNCTION, array($this, 'addResponseHeaderLine')); - $this->response_headers = array(); - $this->response = curl_exec($this->curl); - $this->curl_error_code = curl_errno($this->curl); - $this->curl_error_message = curl_error($this->curl); - $this->curl_error = ! ($this->getErrorCode() === 0); - $this->http_status_code = intval(curl_getinfo($this->curl, CURLINFO_HTTP_CODE)); - $this->http_error = $this->isError(); - $this->error = $this->curl_error || $this->http_error; - $this->error_code = $this->error ? ($this->curl_error ? $this->getErrorCode() : $this->getHttpStatus()) : 0; - $this->request_headers = preg_split( - '/\r\n/', - curl_getinfo($this->curl, CURLINFO_HEADER_OUT), - -1, - PREG_SPLIT_NO_EMPTY - ); - $this->http_error_message = $this->error ? (isset($this->response_headers['0']) ? $this->response_headers['0'] : '') : ''; - $this->error_message = $this->curl_error ? $this->getErrorMessage() : $this->http_error_message; - $this->setOpt(CURLOPT_HEADERFUNCTION, null); - return $this->error_code; - } - - /** - * @param array|object|string $data - */ - protected function preparePayload($data) - { - $this->setOpt(CURLOPT_POST, true); - - if (is_array($data) || is_object($data)) { - $skip = false; - foreach ($data as $key => $value) { - // If a value is an instance of CurlFile skip the http_build_query - // see issue https://github.com/php-mod/curl/issues/46 - // suggestion from: https://stackoverflow.com/a/36603038/4611030 - if ($value instanceof \CurlFile) { - $skip = true; - } - } - - if ( ! $skip) { - $data = http_build_query($data); - } - } - - $this->setOpt(CURLOPT_POSTFIELDS, $data); - } - - /** - * Set the json payload informations to the postfield curl option. - * - * @param array $data The data to be sent. - * - * @return void - */ - protected function prepareJsonPayload(array $data) - { - $this->setOpt(CURLOPT_POST, true); - $this->setOpt(CURLOPT_POSTFIELDS, json_encode($data)); - } - - /** - * Set auth options for the current request. - * - * Available auth types are: - * - * + self::AUTH_BASIC - * + self::AUTH_DIGEST - * + self::AUTH_GSSNEGOTIATE - * + self::AUTH_NTLM - * + self::AUTH_ANY - * + self::AUTH_ANYSAFE - * - * @param int $httpauth The type of authentication - */ - protected function setHttpAuth($httpauth) - { - $this->setOpt(CURLOPT_HTTPAUTH, $httpauth); - } - - // public methods - - /** - * @deprecated use `exec()` directly. Will be removed in 3.0 - */ - public function _exec() - { - return $this->exec(); - } - - // functions - - /** - * Make a get request with optional data. - * - * The get request has no body data, the data will be correctly added to the $url with the http_build_query() method. - * - * @param string $url The url to make the get request for - * @param array $data Optional arguments who are part of the url - * - * @return self - */ - public function get($url, $data = array()) - { - $this->setOpt(CURLOPT_CUSTOMREQUEST, "GET"); - if (count($data) > 0) { - $this->setOpt(CURLOPT_URL, $url . '?' . http_build_query($data)); - } else { - $this->setOpt(CURLOPT_URL, $url); - } - $this->setOpt(CURLOPT_HTTPGET, true); - $this->exec(); - return $this; - } - - /** - * Purge Request - * - * A very common scenario to send a purge request is within the use of varnish, therefore - * the optional hostname can be defined. - * - * @param string $url The url to make the purge request - * @param string $hostName An optional hostname which will be sent as http host header - * - * @return self - * @since 2.4.0 - */ - public function purge($url, $hostName = null) - { - $this->setOpt(CURLOPT_URL, $url); - $this->setOpt(CURLOPT_CUSTOMREQUEST, 'PURGE'); - if ($hostName) { - $this->setHeader('Host', $hostName); - } - $this->exec(); - return $this; - } - - /** - * Make a post request with optional post data. - * - * @param string $url The url to make the post request - * @param array|object|string $data Post data to pass to the url - * @param boolean $asJson Whether the data should be passed as json or not. {@insce 2.2.1} - * - * @return self - */ - public function post($url, $data = array(), $asJson = false) - { - $this->setOpt(CURLOPT_CUSTOMREQUEST, "POST"); - $this->setOpt(CURLOPT_URL, $url); - if ($asJson) { - $this->prepareJsonPayload($data); - } else { - $this->preparePayload($data); - } - $this->exec(); - return $this; - } - - /** - * Make a put request with optional data. - * - * The put request data can be either sent via payload or as get parameters of the string. - * - * @param string $url The url to make the put request - * @param array $data Optional data to pass to the $url - * @param bool $payload Whether the data should be transmitted trough payload or as get parameters of the string - * @param boolean $asJson Whether the data should be passed as json or not. {@insce 2.4.0} - * - * @return self - */ - public function put($url, $data = array(), $payload = false, $asJson = false) - { - if ( ! empty($data)) { - if ($payload === false) { - $url .= '?' . http_build_query($data); - } else { - if ($asJson) { - $this->prepareJsonPayload($data); - } else { - $this->preparePayload($data); - } - } - } - - $this->setOpt(CURLOPT_URL, $url); - $this->setOpt(CURLOPT_CUSTOMREQUEST, 'PUT'); - $this->exec(); - return $this; - } - - /** - * Make a patch request with optional data. - * - * The patch request data can be either sent via payload or as get parameters of the string. - * - * @param string $url The url to make the patch request - * @param array $data Optional data to pass to the $url - * @param bool $payload Whether the data should be transmitted trough payload or as get parameters of the string - * @param boolean $asJson Whether the data should be passed as json or not. {@insce 2.4.0} - * - * @return self - */ - public function patch($url, $data = array(), $payload = false, $asJson = false) - { - if ( ! empty($data)) { - if ($payload === false) { - $url .= '?' . http_build_query($data); - } else { - if ($asJson) { - $this->prepareJsonPayload($data); - } else { - $this->preparePayload($data); - } - } - } - - $this->setOpt(CURLOPT_URL, $url); - $this->setOpt(CURLOPT_CUSTOMREQUEST, 'PATCH'); - $this->exec(); - return $this; - } - - /** - * Make a delete request with optional data. - * - * @param string $url The url to make the delete request - * @param array $data Optional data to pass to the $url - * @param bool $payload Whether the data should be transmitted trough payload or as get parameters of the string - * - * @return self - */ - public function delete($url, $data = array(), $payload = false) - { - if ( ! empty($data)) { - if ($payload === false) { - $url .= '?' . http_build_query($data); - } else { - $this->preparePayload($data); - } - } - - $this->setOpt(CURLOPT_URL, $url); - $this->setOpt(CURLOPT_CUSTOMREQUEST, 'DELETE'); - $this->exec(); - return $this; - } - - // setters - - /** - * Pass basic auth data. - * - * If the the requested url is secured by an htaccess basic auth mechanism you can use this method to provided the auth data. - * - * ```php - * $curl = new Curl(); - * $curl->setBasicAuthentication('john', 'doe'); - * $curl->get('http://example.com/secure.php'); - * ``` - * - * @param string $username The username for the authentication - * @param string $password The password for the given username for the authentication - * - * @return self - */ - public function setBasicAuthentication($username, $password) - { - $this->setHttpAuth(self::AUTH_BASIC); - $this->setOpt(CURLOPT_USERPWD, $username . ':' . $password); - return $this; - } - - /** - * Provide optional header information. - * - * In order to pass optional headers by key value pairing: - * - * ```php - * $curl = new Curl(); - * $curl->setHeader('X-Requested-With', 'XMLHttpRequest'); - * $curl->get('http://example.com/request.php'); - * ``` - * - * @param string $key The header key - * @param string $value The value for the given header key - * - * @return self - */ - public function setHeader($key, $value) - { - $this->_headers[$key] = $key . ': ' . $value; - $this->setOpt(CURLOPT_HTTPHEADER, array_values($this->_headers)); - return $this; - } - - /** - * Provide a User Agent. - * - * In order to provide you customized user agent name you can use this method. - * - * ```php - * $curl = new Curl(); - * $curl->setUserAgent('My John Doe Agent 1.0'); - * $curl->get('http://example.com/request.php'); - * ``` - * - * @param string $useragent The name of the user agent to set for the current request - * - * @return self - */ - public function setUserAgent($useragent) - { - $this->setOpt(CURLOPT_USERAGENT, $useragent); - return $this; - } - - /** - * @param $referrer - * - * @return self - * @deprecated Call setReferer() instead. Will be removed in 3.0 - * - */ - public function setReferrer($referrer) - { - $this->setReferer($referrer); - return $this; - } - - /** - * Set the HTTP referer header. - * - * The $referer Information can help identify the requested client where the requested was made. - * - * @param string $referer An url to pass and will be set as referer header - * - * @return self - */ - public function setReferer($referer) - { - $this->setOpt(CURLOPT_REFERER, $referer); - return $this; - } - - /** - * Set contents of HTTP Cookie header. - * - * @param string $key The name of the cookie - * @param string $value The value for the provided cookie name - * - * @return self - */ - public function setCookie($key, $value) - { - $this->_cookies[$key] = $value; - $this->setOpt(CURLOPT_COOKIE, http_build_query($this->_cookies, '', '; ')); - return $this; - } - - /** - * Set customized curl options. - * - * To see a full list of options: http://php.net/curl_setopt - * - * @see http://php.net/curl_setopt - * - * @param int $option The curl option constant e.g. `CURLOPT_AUTOREFERER`, `CURLOPT_COOKIESESSION` - * @param mixed $value The value to pass for the given $option - * - * @return bool - */ - public function setOpt($option, $value) - { - return curl_setopt($this->curl, $option, $value); - } - - /** - * Get curl option for a certain name - * - * To see a full list of options: http://php.net/curl_getinfo - * - * @see http://php.net/curl_getinfo - * - * @param int $option The curl option constant e.g. `CURLOPT_AUTOREFERER`, `CURLOPT_COOKIESESSION` - * - * @return mixed - */ - public function getOpt($option) - { - return curl_getinfo($this->curl, $option); - } - - /** - * Return the all options for current curl ressource - * - * To see a full list of options: http://php.net/curl_getinfo - * - * @see http://php.net/curl_getinfo - * @return array - * @since 2.5.0 - */ - public function getOpts() - { - return curl_getinfo($this->curl); - } - - /** - * Return the endpoint set for curl - * - * @see http://php.net/curl_getinfo - * @return string of endpoint - */ - public function getEndpoint() - { - return $this->getOpt(CURLINFO_EFFECTIVE_URL); - } - - /** - * Enable verbosity. - * - * @param bool $on - * - * @return self - */ - public function setVerbose($on = true) - { - $this->setOpt(CURLOPT_VERBOSE, $on); - return $this; - } - - /** - * @param bool $on - * - * @return self - * @deprecated Call setVerbose() instead. Will be removed in 3.0 - * - */ - public function verbose($on = true) - { - return $this->setVerbose($on); - } - - /** - * Reset all curl options. - * - * In order to make multiple requests with the same curl object all settings requires to be reset. - * - * @return self - */ - public function reset() - { - $this->close(); - $this->_cookies = array(); - $this->_headers = array(); - $this->error = false; - $this->error_code = 0; - $this->error_message = null; - $this->curl_error = false; - $this->curl_error_code = 0; - $this->curl_error_message = null; - $this->http_error = false; - $this->http_status_code = 0; - $this->http_error_message = null; - $this->request_headers = null; - $this->response_headers = array(); - $this->response = false; - $this->init(); - return $this; - } - - /** - * Closing the current open curl resource. - * - * @return self - */ - public function close() - { - if (is_resource($this->curl)) { - curl_close($this->curl); - } - return $this; - } - - /** - * Close the connection when the Curl object will be destroyed. - */ - public function __destruct() - { - $this->close(); - } - - /** - * Was an 'info' header returned. - * - * @return bool - */ - public function isInfo() - { - return $this->getHttpStatus() >= 100 && $this->getHttpStatus() < 200; - } - - /** - * Was an 'OK' response returned. - * - * @return bool - */ - public function isSuccess() - { - return $this->getHttpStatus() >= 200 && $this->getHttpStatus() < 300; - } - - /** - * Was a 'redirect' returned. - * - * @return bool - */ - public function isRedirect() - { - return $this->getHttpStatus() >= 300 && $this->getHttpStatus() < 400; - } - - /** - * Was an 'error' returned (client error or server error). - * - * @return bool - */ - public function isError() - { - return $this->getHttpStatus() >= 400 && $this->getHttpStatus() < 600; - } - - /** - * Was a 'client error' returned. - * - * @return bool - */ - public function isClientError() - { - return $this->getHttpStatus() >= 400 && $this->getHttpStatus() < 500; - } - - /** - * Was a 'server error' returned. - * - * @return bool - */ - public function isServerError() - { - return $this->getHttpStatus() >= 500 && $this->getHttpStatus() < 600; - } - - /** - * Get a specific response header key or all values from the response headers array. - * - * Usage example: - * - * ```php - * $curl = (new Curl())->get('http://example.com'); - * - * echo $curl->getResponseHeaders('Content-Type'); - * ``` - * - * Or in order to dump all keys with the given values use: - * - * ```php - * $curl = (new Curl())->get('http://example.com'); - * - * var_dump($curl->getResponseHeaders()); - * ``` - * - * @param string $headerKey Optional key to get from the array. - * - * @return bool|string|array - * @since 1.9 - */ - public function getResponseHeaders($headerKey = null) - { - $headers = array(); - if ( ! is_null($headerKey)) { - $headerKey = strtolower($headerKey); - } - - foreach ($this->response_headers as $header) { - $parts = explode(":", $header, 2); - - $key = isset($parts[0]) ? $parts[0] : ''; - $value = isset($parts[1]) ? $parts[1] : ''; - - $headers[strtolower(trim($key))] = trim($value); - } - - if ($headerKey) { - return isset($headers[$headerKey]) ? $headers[$headerKey] : false; - } - - return $headers; - } - - /** - * Get response from the curl request - * - * @return string|false - */ - public function getResponse() - { - return $this->response; - } - - /** - * Get curl error code - * - * @return int - */ - public function getErrorCode() - { - return $this->curl_error_code; - } - - /** - * Get curl error message - * - * @return string - */ - public function getErrorMessage() - { - return $this->curl_error_message; - } - - /** - * Get http status code from the curl request - * - * @return int - */ - public function getHttpStatus() - { - return $this->http_status_code; - } + // The HTTP authentication method(s) to use. + + /** + * @var int Type AUTH_BASIC + */ + const AUTH_BASIC = CURLAUTH_BASIC; + + /** + * @var int Type AUTH_DIGEST + */ + const AUTH_DIGEST = CURLAUTH_DIGEST; + + /** + * @var int Type AUTH_GSSNEGOTIATE + */ + const AUTH_GSSNEGOTIATE = CURLAUTH_GSSNEGOTIATE; + + /** + * @var int Type AUTH_NTLM + */ + const AUTH_NTLM = CURLAUTH_NTLM; + + /** + * @var int Type AUTH_ANY + */ + const AUTH_ANY = CURLAUTH_ANY; + + /** + * @var int Type AUTH_ANYSAFE + */ + const AUTH_ANYSAFE = CURLAUTH_ANYSAFE; + + /** + * @var string The user agent name which is set when making a request + */ + const USER_AGENT = 'PHP Curl/2.6 (+https://github.com/nguyenanhung/codeigniter-basic-helper)'; + + private $_cookies = array(); + + private $_headers = array(); + + /** + * @var resource Contains the curl resource created by `curl_init()` function + */ + public $curl; + + /** + * @var bool Whether an error occurred or not + */ + public $error = false; + + /** + * @var int Contains the error code of the current request, 0 means no error happened + */ + public $error_code = 0; + + /** + * @var string If the curl request failed, the error message is contained + */ + public $error_message = null; + + /** + * @var bool Whether an error occurred or not + */ + public $curl_error = false; + + /** + * @var int Contains the error code of the current request, 0 means no error happened. + * @see https://curl.haxx.se/libcurl/c/libcurl-errors.html + */ + public $curl_error_code = 0; + + /** + * @var string If the curl request failed, the error message is contained + */ + public $curl_error_message = null; + + /** + * @var bool Whether an error occurred or not + */ + public $http_error = false; + + /** + * @var int Contains the status code of the current processed request. + */ + public $http_status_code = 0; + + /** + * @var string If the curl request failed, the error message is contained + */ + public $http_error_message = null; + + /** + * @var string|array TBD (ensure type) Contains the request header information + */ + public $request_headers = null; + + /** + * @var string|array TBD (ensure type) Contains the response header information + */ + public $response_headers = array(); + + /** + * @var string|false|null Contains the response from the curl request + */ + public $response = null; + + /** + * @var bool Whether the current section of response headers is after 'HTTP/1.1 100 Continue' + */ + protected $response_header_continue = false; + + /** + * Constructor ensures the available curl extension is loaded. + * + * @throws \RuntimeException + */ + public function __construct() + { + if (!extension_loaded('curl')) { + throw new \RuntimeException( + 'The cURL extensions is not loaded, make sure you have installed the cURL extension: https://php.net/manual/curl.setup.php' + ); + } + + $this->init(); + } + + // private methods + + /** + * Initializer for the curl resource. + * + * Is called by the __construct() of the class or when the curl request is reset. + * + * @return self + */ + private function init() + { + $this->curl = curl_init(); + $this->setUserAgent(self::USER_AGENT); + $this->setOpt(CURLINFO_HEADER_OUT, true); + $this->setOpt(CURLOPT_HEADER, false); + $this->setOpt(CURLOPT_RETURNTRANSFER, true); + + return $this; + } + + /** + * Handle writing the response headers + * + * @param resource $curl The current curl resource + * @param string $header_line A line from the list of response headers + * + * @return int Returns the length of the $header_line + */ + public function addResponseHeaderLine($curl, $header_line) + { + $trimmed_header = trim($header_line, "\r\n"); + + if ($trimmed_header === "") { + $this->response_header_continue = false; + } elseif (strtolower($trimmed_header) === 'http/1.1 100 continue') { + $this->response_header_continue = true; + } elseif (!$this->response_header_continue) { + $this->response_headers[] = $trimmed_header; + } + + return strlen($header_line); + } + + // protected methods + + /** + * Execute the curl request based on the respective settings. + * + * @return int Returns the error code for the current curl request + */ + public function exec() + { + $this->setOpt(CURLOPT_HEADERFUNCTION, array($this, 'addResponseHeaderLine')); + $this->response_headers = array(); + $this->response = curl_exec($this->curl); + $this->curl_error_code = curl_errno($this->curl); + $this->curl_error_message = curl_error($this->curl); + $this->curl_error = !($this->getErrorCode() === 0); + $this->http_status_code = intval(curl_getinfo($this->curl, CURLINFO_HTTP_CODE)); + $this->http_error = $this->isError(); + $this->error = $this->curl_error || $this->http_error; + $this->error_code = $this->error ? ($this->curl_error ? $this->getErrorCode() : $this->getHttpStatus()) : 0; + $this->request_headers = preg_split( + '/\r\n/', + curl_getinfo($this->curl, CURLINFO_HEADER_OUT), + -1, + PREG_SPLIT_NO_EMPTY + ); + $this->http_error_message = $this->error ? (isset($this->response_headers['0']) ? $this->response_headers['0'] : '') : ''; + $this->error_message = $this->curl_error ? $this->getErrorMessage() : $this->http_error_message; + $this->setOpt(CURLOPT_HEADERFUNCTION, null); + return $this->error_code; + } + + /** + * @param array|object|string $data + */ + protected function preparePayload($data) + { + $this->setOpt(CURLOPT_POST, true); + + if (is_array($data) || is_object($data)) { + $skip = false; + foreach ($data as $key => $value) { + // If a value is an instance of CurlFile skip the http_build_query + // see issue https://github.com/php-mod/curl/issues/46 + // suggestion from: https://stackoverflow.com/a/36603038/4611030 + if ($value instanceof \CurlFile) { + $skip = true; + } + } + + if (!$skip) { + $data = http_build_query($data); + } + } + + $this->setOpt(CURLOPT_POSTFIELDS, $data); + } + + /** + * Set the json payload informations to the postfield curl option. + * + * @param array $data The data to be sent. + * + * @return void + */ + protected function prepareJsonPayload(array $data) + { + $this->setOpt(CURLOPT_POST, true); + $this->setOpt(CURLOPT_POSTFIELDS, json_encode($data)); + } + + /** + * Set auth options for the current request. + * + * Available auth types are: + * + * + self::AUTH_BASIC + * + self::AUTH_DIGEST + * + self::AUTH_GSSNEGOTIATE + * + self::AUTH_NTLM + * + self::AUTH_ANY + * + self::AUTH_ANYSAFE + * + * @param int $httpauth The type of authentication + */ + protected function setHttpAuth($httpauth) + { + $this->setOpt(CURLOPT_HTTPAUTH, $httpauth); + } + + // public methods + + /** + * @deprecated use `exec()` directly. Will be removed in 3.0 + */ + public function _exec() + { + return $this->exec(); + } + + // functions + + /** + * Make a get request with optional data. + * + * The get request has no body data, the data will be correctly added to the $url with the http_build_query() method. + * + * @param string $url The url to make the get request for + * @param array $data Optional arguments who are part of the url + * + * @return self + */ + public function get($url, $data = array()) + { + $this->setOpt(CURLOPT_CUSTOMREQUEST, "GET"); + if (count($data) > 0) { + $this->setOpt(CURLOPT_URL, $url . '?' . http_build_query($data)); + } else { + $this->setOpt(CURLOPT_URL, $url); + } + $this->setOpt(CURLOPT_HTTPGET, true); + $this->exec(); + return $this; + } + + /** + * Purge Request + * + * A very common scenario to send a purge request is within the use of varnish, therefore + * the optional hostname can be defined. + * + * @param string $url The url to make the purge request + * @param string $hostName An optional hostname which will be sent as http host header + * + * @return self + * @since 2.4.0 + */ + public function purge($url, $hostName = null) + { + $this->setOpt(CURLOPT_URL, $url); + $this->setOpt(CURLOPT_CUSTOMREQUEST, 'PURGE'); + if ($hostName) { + $this->setHeader('Host', $hostName); + } + $this->exec(); + return $this; + } + + /** + * Make a post request with optional post data. + * + * @param string $url The url to make the post request + * @param array|object|string $data Post data to pass to the url + * @param boolean $asJson Whether the data should be passed as json or not. {@insce 2.2.1} + * + * @return self + */ + public function post($url, $data = array(), $asJson = false) + { + $this->setOpt(CURLOPT_CUSTOMREQUEST, "POST"); + $this->setOpt(CURLOPT_URL, $url); + if ($asJson) { + $this->prepareJsonPayload($data); + } else { + $this->preparePayload($data); + } + $this->exec(); + return $this; + } + + /** + * Make a put request with optional data. + * + * The put request data can be either sent via payload or as get parameters of the string. + * + * @param string $url The url to make the put request + * @param array $data Optional data to pass to the $url + * @param bool $payload Whether the data should be transmitted trough payload or as get parameters of the string + * @param boolean $asJson Whether the data should be passed as json or not. {@insce 2.4.0} + * + * @return self + */ + public function put($url, $data = array(), $payload = false, $asJson = false) + { + if (!empty($data)) { + if ($payload === false) { + $url .= '?' . http_build_query($data); + } else { + if ($asJson) { + $this->prepareJsonPayload($data); + } else { + $this->preparePayload($data); + } + } + } + + $this->setOpt(CURLOPT_URL, $url); + $this->setOpt(CURLOPT_CUSTOMREQUEST, 'PUT'); + $this->exec(); + return $this; + } + + /** + * Make a patch request with optional data. + * + * The patch request data can be either sent via payload or as get parameters of the string. + * + * @param string $url The url to make the patch request + * @param array $data Optional data to pass to the $url + * @param bool $payload Whether the data should be transmitted trough payload or as get parameters of the string + * @param boolean $asJson Whether the data should be passed as json or not. {@insce 2.4.0} + * + * @return self + */ + public function patch($url, $data = array(), $payload = false, $asJson = false) + { + if (!empty($data)) { + if ($payload === false) { + $url .= '?' . http_build_query($data); + } else { + if ($asJson) { + $this->prepareJsonPayload($data); + } else { + $this->preparePayload($data); + } + } + } + + $this->setOpt(CURLOPT_URL, $url); + $this->setOpt(CURLOPT_CUSTOMREQUEST, 'PATCH'); + $this->exec(); + return $this; + } + + /** + * Make a delete request with optional data. + * + * @param string $url The url to make the delete request + * @param array $data Optional data to pass to the $url + * @param bool $payload Whether the data should be transmitted trough payload or as get parameters of the string + * + * @return self + */ + public function delete($url, $data = array(), $payload = false) + { + if (!empty($data)) { + if ($payload === false) { + $url .= '?' . http_build_query($data); + } else { + $this->preparePayload($data); + } + } + + $this->setOpt(CURLOPT_URL, $url); + $this->setOpt(CURLOPT_CUSTOMREQUEST, 'DELETE'); + $this->exec(); + return $this; + } + + // setters + + /** + * Pass basic auth data. + * + * If the the requested url is secured by an htaccess basic auth mechanism you can use this method to provided the auth data. + * + * ```php + * $curl = new Curl(); + * $curl->setBasicAuthentication('john', 'doe'); + * $curl->get('http://example.com/secure.php'); + * ``` + * + * @param string $username The username for the authentication + * @param string $password The password for the given username for the authentication + * + * @return self + */ + public function setBasicAuthentication($username, $password) + { + $this->setHttpAuth(self::AUTH_BASIC); + $this->setOpt(CURLOPT_USERPWD, $username . ':' . $password); + return $this; + } + + /** + * Provide optional header information. + * + * In order to pass optional headers by key value pairing: + * + * ```php + * $curl = new Curl(); + * $curl->setHeader('X-Requested-With', 'XMLHttpRequest'); + * $curl->get('http://example.com/request.php'); + * ``` + * + * @param string $key The header key + * @param string $value The value for the given header key + * + * @return self + */ + public function setHeader($key, $value) + { + $this->_headers[$key] = $key . ': ' . $value; + $this->setOpt(CURLOPT_HTTPHEADER, array_values($this->_headers)); + return $this; + } + + /** + * Provide a User Agent. + * + * In order to provide you customized user agent name you can use this method. + * + * ```php + * $curl = new Curl(); + * $curl->setUserAgent('My John Doe Agent 1.0'); + * $curl->get('http://example.com/request.php'); + * ``` + * + * @param string $useragent The name of the user agent to set for the current request + * + * @return self + */ + public function setUserAgent($useragent) + { + $this->setOpt(CURLOPT_USERAGENT, $useragent); + return $this; + } + + /** + * @param $referrer + * + * @return self + * @deprecated Call setReferer() instead. Will be removed in 3.0 + * + */ + public function setReferrer($referrer) + { + $this->setReferer($referrer); + return $this; + } + + /** + * Set the HTTP referer header. + * + * The $referer Information can help identify the requested client where the requested was made. + * + * @param string $referer An url to pass and will be set as referer header + * + * @return self + */ + public function setReferer($referer) + { + $this->setOpt(CURLOPT_REFERER, $referer); + return $this; + } + + /** + * Set contents of HTTP Cookie header. + * + * @param string $key The name of the cookie + * @param string $value The value for the provided cookie name + * + * @return self + */ + public function setCookie($key, $value) + { + $this->_cookies[$key] = $value; + $this->setOpt(CURLOPT_COOKIE, http_build_query($this->_cookies, '', '; ')); + return $this; + } + + /** + * Set customized curl options. + * + * To see a full list of options: http://php.net/curl_setopt + * + * @see http://php.net/curl_setopt + * + * @param int $option The curl option constant e.g. `CURLOPT_AUTOREFERER`, `CURLOPT_COOKIESESSION` + * @param mixed $value The value to pass for the given $option + * + * @return bool + */ + public function setOpt($option, $value) + { + return curl_setopt($this->curl, $option, $value); + } + + /** + * Get curl option for a certain name + * + * To see a full list of options: http://php.net/curl_getinfo + * + * @see http://php.net/curl_getinfo + * + * @param int $option The curl option constant e.g. `CURLOPT_AUTOREFERER`, `CURLOPT_COOKIESESSION` + * + * @return mixed + */ + public function getOpt($option) + { + return curl_getinfo($this->curl, $option); + } + + /** + * Return the all options for current curl ressource + * + * To see a full list of options: http://php.net/curl_getinfo + * + * @see http://php.net/curl_getinfo + * @return array + * @since 2.5.0 + */ + public function getOpts() + { + return curl_getinfo($this->curl); + } + + /** + * Return the endpoint set for curl + * + * @see http://php.net/curl_getinfo + * @return string of endpoint + */ + public function getEndpoint() + { + return $this->getOpt(CURLINFO_EFFECTIVE_URL); + } + + /** + * Enable verbosity. + * + * @param bool $on + * + * @return self + */ + public function setVerbose($on = true) + { + $this->setOpt(CURLOPT_VERBOSE, $on); + return $this; + } + + /** + * @param bool $on + * + * @return self + * @deprecated Call setVerbose() instead. Will be removed in 3.0 + * + */ + public function verbose($on = true) + { + return $this->setVerbose($on); + } + + /** + * Reset all curl options. + * + * In order to make multiple requests with the same curl object all settings requires to be reset. + * + * @return self + */ + public function reset() + { + $this->close(); + $this->_cookies = array(); + $this->_headers = array(); + $this->error = false; + $this->error_code = 0; + $this->error_message = null; + $this->curl_error = false; + $this->curl_error_code = 0; + $this->curl_error_message = null; + $this->http_error = false; + $this->http_status_code = 0; + $this->http_error_message = null; + $this->request_headers = null; + $this->response_headers = array(); + $this->response = false; + $this->init(); + return $this; + } + + /** + * Closing the current open curl resource. + * + * @return self + */ + public function close() + { + if (is_resource($this->curl)) { + curl_close($this->curl); + } + return $this; + } + + /** + * Close the connection when the Curl object will be destroyed. + */ + public function __destruct() + { + $this->close(); + } + + /** + * Was an 'info' header returned. + * + * @return bool + */ + public function isInfo() + { + return $this->getHttpStatus() >= 100 && $this->getHttpStatus() < 200; + } + + /** + * Was an 'OK' response returned. + * + * @return bool + */ + public function isSuccess() + { + return $this->getHttpStatus() >= 200 && $this->getHttpStatus() < 300; + } + + /** + * Was a 'redirect' returned. + * + * @return bool + */ + public function isRedirect() + { + return $this->getHttpStatus() >= 300 && $this->getHttpStatus() < 400; + } + + /** + * Was an 'error' returned (client error or server error). + * + * @return bool + */ + public function isError() + { + return $this->getHttpStatus() >= 400 && $this->getHttpStatus() < 600; + } + + /** + * Was a 'client error' returned. + * + * @return bool + */ + public function isClientError() + { + return $this->getHttpStatus() >= 400 && $this->getHttpStatus() < 500; + } + + /** + * Was a 'server error' returned. + * + * @return bool + */ + public function isServerError() + { + return $this->getHttpStatus() >= 500 && $this->getHttpStatus() < 600; + } + + /** + * Get a specific response header key or all values from the response headers array. + * + * Usage example: + * + * ```php + * $curl = (new Curl())->get('http://example.com'); + * + * echo $curl->getResponseHeaders('Content-Type'); + * ``` + * + * Or in order to dump all keys with the given values use: + * + * ```php + * $curl = (new Curl())->get('http://example.com'); + * + * var_dump($curl->getResponseHeaders()); + * ``` + * + * @param string $headerKey Optional key to get from the array. + * + * @return bool|string|array + * @since 1.9 + */ + public function getResponseHeaders($headerKey = null) + { + $headers = array(); + if (!is_null($headerKey)) { + $headerKey = strtolower($headerKey); + } + + foreach ($this->response_headers as $header) { + $parts = explode(":", $header, 2); + + $key = isset($parts[0]) ? $parts[0] : ''; + $value = isset($parts[1]) ? $parts[1] : ''; + + $headers[strtolower(trim($key))] = trim($value); + } + + if ($headerKey) { + return isset($headers[$headerKey]) ? $headers[$headerKey] : false; + } + + return $headers; + } + + /** + * Get response from the curl request + * + * @return string|false + */ + public function getResponse() + { + return $this->response; + } + + /** + * Get curl error code + * + * @return int + */ + public function getErrorCode() + { + return $this->curl_error_code; + } + + /** + * Get curl error message + * + * @return string + */ + public function getErrorMessage() + { + return $this->curl_error_message; + } + + /** + * Get http status code from the curl request + * + * @return int + */ + public function getHttpStatus() + { + return $this->http_status_code; + } } diff --git a/src/BasicImageHelperWithGD.php b/src/BasicImageHelperWithGD.php index e5f65ce..154b557 100644 --- a/src/BasicImageHelperWithGD.php +++ b/src/BasicImageHelperWithGD.php @@ -12,90 +12,90 @@ class BasicImageHelperWithGD { - protected $image; + protected $image; - protected $imageFormat; + protected $imageFormat; - public function load($imageFile) - { - $imageInfo = getImageSize($imageFile); - $this->imageFormat = $imageInfo[2]; + public function load($imageFile) + { + $imageInfo = getImageSize($imageFile); + $this->imageFormat = $imageInfo[2]; - if ($this->imageFormat === IMAGETYPE_JPEG) { - $this->image = imagecreatefromjpeg($imageFile); - } elseif ($this->imageFormat === IMAGETYPE_GIF) { - $this->image = imagecreatefromgif($imageFile); - } elseif ($this->imageFormat === IMAGETYPE_PNG) { - $this->image = imagecreatefrompng($imageFile); - } - } + if ($this->imageFormat === IMAGETYPE_JPEG) { + $this->image = imagecreatefromjpeg($imageFile); + } elseif ($this->imageFormat === IMAGETYPE_GIF) { + $this->image = imagecreatefromgif($imageFile); + } elseif ($this->imageFormat === IMAGETYPE_PNG) { + $this->image = imagecreatefrompng($imageFile); + } + } - public function save($imageFile, $imageFormat = IMAGETYPE_JPEG, $compression = 75, $permissions = null) - { - if ($imageFormat == IMAGETYPE_JPEG) { - imagejpeg($this->image, $imageFile, $compression); - } elseif ($imageFormat == IMAGETYPE_GIF) { - imagegif($this->image, $imageFile); - } elseif ($imageFormat == IMAGETYPE_PNG) { - imagepng($this->image, $imageFile); - } - if ($permissions != null) { - chmod($imageFile, $permissions); - } - } + public function save($imageFile, $imageFormat = IMAGETYPE_JPEG, $compression = 75, $permissions = null) + { + if ($imageFormat == IMAGETYPE_JPEG) { + imagejpeg($this->image, $imageFile, $compression); + } elseif ($imageFormat == IMAGETYPE_GIF) { + imagegif($this->image, $imageFile); + } elseif ($imageFormat == IMAGETYPE_PNG) { + imagepng($this->image, $imageFile); + } + if ($permissions != null) { + chmod($imageFile, $permissions); + } + } - public function getWidth() - { - return imagesx($this->image); - } + public function getWidth() + { + return imagesx($this->image); + } - public function getHeight() - { - return imagesy($this->image); - } + public function getHeight() + { + return imagesy($this->image); + } - public function resizeToHeight($height) - { - $ratio = $height / $this->getHeight(); - $width = $this->getWidth() * $ratio; - $this->resized($width, $height); - } + public function resizeToHeight($height) + { + $ratio = $height / $this->getHeight(); + $width = $this->getWidth() * $ratio; + $this->resized($width, $height); + } - public function resizeToWidth($width) - { - $ratio = $width / $this->getWidth(); - $height = $this->getheight() * $ratio; - $this->resized( - $width, - $height - ); - } + public function resizeToWidth($width) + { + $ratio = $width / $this->getWidth(); + $height = $this->getheight() * $ratio; + $this->resized( + $width, + $height + ); + } - public function scale($scale) - { - $width = $this->getWidth() * $scale / 100; - $height = $this->getheight() * $scale / 100; - $this->resized( - $width, - $height - ); - } + public function scale($scale) + { + $width = $this->getWidth() * $scale / 100; + $height = $this->getheight() * $scale / 100; + $this->resized( + $width, + $height + ); + } - protected function resized($width, $height) - { - $newImage = imagecreatetruecolor($width, $height); - imagecopyresampled( - $newImage, - $this->image, - 0, - 0, - 0, - 0, - $width, - $height, - $this->getWidth(), - $this->getHeight() - ); - $this->image = $newImage; - } + protected function resized($width, $height) + { + $newImage = imagecreatetruecolor($width, $height); + imagecopyresampled( + $newImage, + $this->image, + 0, + 0, + 0, + 0, + $width, + $height, + $this->getWidth(), + $this->getHeight() + ); + $this->image = $newImage; + } } diff --git a/src/ChartRender.php b/src/ChartRender.php index 3135c76..18853c4 100644 --- a/src/ChartRender.php +++ b/src/ChartRender.php @@ -14,18 +14,18 @@ class ChartRender extends BaseHelper { - protected function misc() - { - return new Miscellaneous(); - } + protected function misc() + { + return new Miscellaneous(); + } - public function get_data_chart($item_list, $valueGet, $total) - { - return $this->misc()->metronic_get_data_chart($item_list, $valueGet, $total); - } + public function get_data_chart($item_list, $valueGet, $total) + { + return $this->misc()->metronic_get_data_chart($item_list, $valueGet, $total); + } - public function get_data_chart_report($item_list, $valueGet) - { - return $this->misc()->metronic_get_data_chart_report($item_list, $valueGet); - } + public function get_data_chart_report($item_list, $valueGet) + { + return $this->misc()->metronic_get_data_chart_report($item_list, $valueGet); + } } diff --git a/src/Favicon.php b/src/Favicon.php index 2f00001..36b9edf 100644 --- a/src/Favicon.php +++ b/src/Favicon.php @@ -19,45 +19,45 @@ */ final class Favicon extends BaseHelper { - /** - * Function faviconHtml - * - * Function này hỗ trợ return ra 1 đoạn HTML dùng show Favicon, được build từ https://www.favicon-generator.org/ - * - * @param $baseUrl - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 30/12/2022 00:06 - * - * @see : https://www.favicon-generator.org/ - */ - public function faviconHtml($baseUrl = '') - { - $baseUrl = trim($baseUrl) . '/'; - $html = '' . PHP_EOL; - $html .= '' . PHP_EOL; - $html .= '' . PHP_EOL; - $html .= '' . PHP_EOL; - $html .= '' . PHP_EOL; - $html .= '' . PHP_EOL; - $html .= '' . PHP_EOL; - $html .= '' . PHP_EOL; - $html .= '' . PHP_EOL; - $html .= '' . PHP_EOL; - $html .= '' . PHP_EOL; - $html .= '' . PHP_EOL; - $html .= '' . PHP_EOL; - $html .= '' . PHP_EOL; - $html .= '' . PHP_EOL; - $html .= '' . PHP_EOL; - $html .= '' . PHP_EOL; - return $html; - } + /** + * Function faviconHtml + * + * Function này hỗ trợ return ra 1 đoạn HTML dùng show Favicon, được build từ https://www.favicon-generator.org/ + * + * @param $baseUrl + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 30/12/2022 00:06 + * + * @see : https://www.favicon-generator.org/ + */ + public function faviconHtml($baseUrl = '') + { + $baseUrl = trim($baseUrl) . '/'; + $html = '' . PHP_EOL; + $html .= '' . PHP_EOL; + $html .= '' . PHP_EOL; + $html .= '' . PHP_EOL; + $html .= '' . PHP_EOL; + $html .= '' . PHP_EOL; + $html .= '' . PHP_EOL; + $html .= '' . PHP_EOL; + $html .= '' . PHP_EOL; + $html .= '' . PHP_EOL; + $html .= '' . PHP_EOL; + $html .= '' . PHP_EOL; + $html .= '' . PHP_EOL; + $html .= '' . PHP_EOL; + $html .= '' . PHP_EOL; + $html .= '' . PHP_EOL; + $html .= '' . PHP_EOL; + return $html; + } - public static function html($baseUrl = '') - { - return (new self)->faviconHtml($baseUrl); - } + public static function html($baseUrl = '') + { + return (new self)->faviconHtml($baseUrl); + } } diff --git a/src/HelperException.php b/src/HelperException.php index 53f2220..ff3e2c9 100644 --- a/src/HelperException.php +++ b/src/HelperException.php @@ -12,15 +12,15 @@ class HelperException extends \Exception { - /** - * @throws \nguyenanhung\CodeIgniter\BasicHelper\HelperException - */ - public function __construct($message = null, $code = 0) - { - if ( ! $message) { - throw new $this('Unknown ' . get_class($this)); - } - $error_message = $message . ' - If you believe this is a codebase or framework bug, please report it and let us know here: ' . BaseHelper::GITHUB_ISSUES_URL . ' - Codebase will be improved by your contributions. Thank you!'; - parent::__construct($error_message, $code); - } + /** + * @throws \nguyenanhung\CodeIgniter\BasicHelper\HelperException + */ + public function __construct($message = null, $code = 0) + { + if (!$message) { + throw new $this('Unknown ' . get_class($this)); + } + $error_message = $message . ' - If you believe this is a codebase or framework bug, please report it and let us know here: ' . BaseHelper::GITHUB_ISSUES_URL . ' - Codebase will be improved by your contributions. Thank you!'; + parent::__construct($error_message, $code); + } } diff --git a/src/ImageHelper.php b/src/ImageHelper.php index 4664459..c7b70b9 100644 --- a/src/ImageHelper.php +++ b/src/ImageHelper.php @@ -21,48 +21,48 @@ */ class ImageHelper extends BaseHelper { - public static function googleGadgetsProxyServerList() - { - return ImageHelperLib::googleGadgetsProxyServerList(); - } + public static function googleGadgetsProxyServerList() + { + return ImageHelperLib::googleGadgetsProxyServerList(); + } - public static function wordpressProxyProxyServerList() - { - return ImageHelperLib::wordpressProxyProxyServerList(); - } + public static function wordpressProxyProxyServerList() + { + return ImageHelperLib::wordpressProxyProxyServerList(); + } - public static function googleGadgetsProxy($url = '', $width = 100, $height = null, $server = 'images1') - { - return ImageHelperLib::googleGadgetsProxy($url, $width, $height, $server); - } + public static function googleGadgetsProxy($url = '', $width = 100, $height = null, $server = 'images1') + { + return ImageHelperLib::googleGadgetsProxy($url, $width, $height, $server); + } - public static function googleGadgetsProxyDnsPrefetch($server = 'images1') - { - return ImageHelperLib::googleGadgetsProxyDnsPrefetch($server); - } + public static function googleGadgetsProxyDnsPrefetch($server = 'images1') + { + return ImageHelperLib::googleGadgetsProxyDnsPrefetch($server); + } - public static function wordpressProxy($imageUrl = '', $server = 'i3', $width = null, $height = null) - { - return ImageHelperLib::wordpressProxy($imageUrl, $server, $width, $height); - } + public static function wordpressProxy($imageUrl = '', $server = 'i3', $width = null, $height = null) + { + return ImageHelperLib::wordpressProxy($imageUrl, $server, $width, $height); + } - public static function wordpressProxyDnsPrefetch() - { - return ImageHelperLib::wordpressProxyDnsPrefetch(); - } + public static function wordpressProxyDnsPrefetch() + { + return ImageHelperLib::wordpressProxyDnsPrefetch(); + } - public static function createThumbnail($url = '', $width = 100, $height = 100) - { - return ImageHelperLib::createThumbnail($url, $width, $height); - } + public static function createThumbnail($url = '', $width = 100, $height = 100) + { + return ImageHelperLib::createThumbnail($url, $width, $height); + } - public static function createThumbnailWithCodeIgniterCache($url = '', $width = 100, $height = 100) - { - return ImageHelperLib::createThumbnailWithCodeIgniterCache($url, $width, $height); - } + public static function createThumbnailWithCodeIgniterCache($url = '', $width = 100, $height = 100) + { + return ImageHelperLib::createThumbnailWithCodeIgniterCache($url, $width, $height); + } - public static function formatImageUrl($input = '', $server = '', $base = 'live') - { - return ImageHelperLib::formatImageUrl($input, $server, $base); - } + public static function formatImageUrl($input = '', $server = '', $base = 'live') + { + return ImageHelperLib::formatImageUrl($input, $server, $base); + } } diff --git a/src/JapanUtils.php b/src/JapanUtils.php index 1060709..0cf9c89 100644 --- a/src/JapanUtils.php +++ b/src/JapanUtils.php @@ -12,17 +12,17 @@ class JapanUtils extends BaseHelper { - public static function getData($configName) - { - $path = __DIR__ . '/japan/' . trim($configName) . '.php'; - if (is_file($path) && file_exists($path)) { - return require $path; - } - return array(); - } + public static function getData($configName) + { + $path = __DIR__ . '/japan/' . trim($configName) . '.php'; + if (is_file($path) && file_exists($path)) { + return require $path; + } + return array(); + } - public static function getJapanPrefCode() - { - return self::getData('pref_code'); - } + public static function getJapanPrefCode() + { + return self::getData('pref_code'); + } } diff --git a/src/ServerReport.php b/src/ServerReport.php index aef7b8e..d103bac 100644 --- a/src/ServerReport.php +++ b/src/ServerReport.php @@ -12,57 +12,57 @@ class ServerReport extends BaseHelper { - public static function report() - { - return array( - 'os_report' => self::os_report(), - 'memory_report' => self::memory_report(), - 'disk_report' => self::disk_report(), - ); - } + public static function report() + { + return array( + 'os_report' => self::os_report(), + 'memory_report' => self::memory_report(), + 'disk_report' => self::disk_report(), + ); + } - public static function disk_report($directory = '/') - { - return array( - 'raw_data' => array( - 'free_space' => disk_free_space($directory), - 'total_space' => disk_total_space($directory) - ), - 'data' => array( - 'free_space' => formatSizeUnits(disk_free_space($directory)), - 'total_space' => formatSizeUnits(disk_total_space($directory)) - ), - 'message' => array( - 'text' => 'Free: ' . formatSizeUnits(disk_free_space($directory)) . ' / Total: ' . formatSizeUnits( - disk_total_space($directory) - ) - ) - ); - } + public static function disk_report($directory = '/') + { + return array( + 'raw_data' => array( + 'free_space' => disk_free_space($directory), + 'total_space' => disk_total_space($directory) + ), + 'data' => array( + 'free_space' => formatSizeUnits(disk_free_space($directory)), + 'total_space' => formatSizeUnits(disk_total_space($directory)) + ), + 'message' => array( + 'text' => 'Free: ' . formatSizeUnits(disk_free_space($directory)) . ' / Total: ' . formatSizeUnits( + disk_total_space($directory) + ) + ) + ); + } - public static function memory_report() - { - return array( - 'raw_data' => array( - 'memory_usage' => memory_get_usage(), - 'memory_peak_usage' => memory_get_peak_usage() - ), - 'data' => array( - 'memory_usage' => formatSizeUnits(memory_get_usage()), - 'memory_peak_usage' => formatSizeUnits(memory_get_peak_usage()) - ), - ); - } + public static function memory_report() + { + return array( + 'raw_data' => array( + 'memory_usage' => memory_get_usage(), + 'memory_peak_usage' => memory_get_peak_usage() + ), + 'data' => array( + 'memory_usage' => formatSizeUnits(memory_get_usage()), + 'memory_peak_usage' => formatSizeUnits(memory_get_peak_usage()) + ), + ); + } - public static function os_report() - { - return array( - 'raw_data' => array( - 'php_uname' => php_uname(), - ), - 'data' => array( - 'php_uname' => php_uname(), - ), - ); - } + public static function os_report() + { + return array( + 'raw_data' => array( + 'php_uname' => php_uname(), + ), + 'data' => array( + 'php_uname' => php_uname(), + ), + ); + } } diff --git a/src/SimpleCurl.php b/src/SimpleCurl.php index ba1c2b8..6c1c44f 100644 --- a/src/SimpleCurl.php +++ b/src/SimpleCurl.php @@ -19,326 +19,326 @@ */ final class SimpleCurl extends BaseHelper { - protected $userAgent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36'; - protected $url; - protected $data; - protected $followLocation; - protected $timeout; - protected $maxRedirects; - protected $cookieFileLocation; - protected $disableSslVerifyHost; - protected $disableSslVerifyPeer; - protected $sslVerifyHost; - protected $sslVerifyPeer; - protected $sslCaInfoFile; - protected $sslVersion; - protected $xml; - protected $json; - protected $post; - protected $postFields; - protected $referer = ""; - protected $session; - protected $webpage; - protected $headers; - protected $headerOut; - protected $includeHeader; - protected $noBody; - protected $status; - protected $isError = false; - protected $error; - protected $binaryTransfer; - protected $userOptions; - protected $authentication = 0; - protected $authUsername = ''; - protected $authPassword = ''; - - /** - * SimpleCurl constructor. - * - * @param string $url - * @param array $options - * - * @author : 713uk13m - * @copyright: 713uk13m - */ - public function __construct($url = '', $options = array()) - { - $this->url = $url; - $this->followLocation = true; - $this->timeout = 180; - $this->maxRedirects = 10; - $this->noBody = false; - $this->includeHeader = false; - $this->headerOut = true; - $this->binaryTransfer = false; - $this->headers[] = "Connection: keep-alive"; - $this->headers[] = "Keep-Alive: 300"; - $this->headers[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7"; - $this->headers[] = "Accept-Language: en-us,en;q=0.5"; - $this->userOptions = $options; - } - - public function setBinaryTransfer($binaryTransfer = true) - { - $this->binaryTransfer = $binaryTransfer; - - return $this; - } - - public function setCookieFileLocation($cookieFileLocation = '') - { - $this->cookieFileLocation = $cookieFileLocation; - - return $this; - } - - public function useAuth($use) - { - $this->authentication = 0; - if ($use === true) { - $this->authentication = 1; - } - - return $this; - } - - public function setAuthUsername($authUsername) - { - $this->authUsername = $authUsername; - - return $this; - } - - public function setAuthPassword($authPassword) - { - $this->authPassword = $authPassword; - - return $this; - } - - public function setUrl($url) - { - $this->url = $url; - - return $this; - } - - public function setReferer($referer) - { - $this->referer = $referer; - - return $this; - } - - public function setHeader($header) - { - $this->headers[] = $header; - - return $this; - } - - public function includeHeader($includeHeader = true) - { - $this->includeHeader = $includeHeader; - - return $this; - } - - public function setPost($postFields) - { - if (is_array($postFields)) { - $postFields = http_build_query($postFields); - } - $this->post = true; - $this->postFields = $postFields; - - return $this; - } - - public function setJson($postFields) - { - if (is_array($postFields) || is_object($postFields)) { - $postFields = json_encode($postFields); - } - $this->json = true; - $this->postFields = $postFields; - $this->headers[] = "Accept: application/json; charset=utf-8"; - $this->headers[] = "Content-Type: application/json; charset=utf-8"; - - return $this; - } - - public function setXml($xmlData) - { - $this->xml = true; - $this->postFields = $xmlData; - $this->headers[] = "Accept: text/xml; charset=utf-8"; - $this->headers[] = "Content-Type: text/xml; charset=utf-8"; - - return $this; - } - - public function setData($data) - { - $this->data = $data; - - return $this; - } - - public function setUserAgent($userAgent) - { - $this->userAgent = $userAgent; - - return $this; - } - - /** - * @see https://curl.se/libcurl/c/CURLOPT_SSL_VERIFYHOST.html - */ - public function disabledSslVerifyHost() - { - $this->disableSslVerifyHost = true; - - return $this; - } - - /** - * @see https://curl.se/libcurl/c/CURLOPT_SSL_VERIFYPEER.html - * @see https://www.saotn.org/dont-turn-off-curlopt_ssl_verifypeer-fix-php-configuration/#gsc.tab=0 - */ - public function disabledSslVerifyPeer() - { - $this->disableSslVerifyPeer = true; - - return $this; - } - - public function enabledSslVerifyPeer($certificateFile) - { - $this->sslVerifyPeer = true; - $this->sslCaInfoFile = $certificateFile; - - return $this; - } - - /** - * @see https://www.php.net/manual/en/function.curl-setopt.php - */ - public function setSslVersion($sslVersion) - { - $this->sslVersion = $sslVersion; - - return $this; - } - - public function createCurl($url = null) - { - if ($url !== null) { - $this->url = $url; - } - - $s = curl_init(); - curl_setopt($s, CURLOPT_URL, $this->url); - curl_setopt($s, CURLOPT_HTTPHEADER, $this->headers); - curl_setopt($s, CURLOPT_TIMEOUT, $this->timeout); - curl_setopt($s, CURLOPT_MAXREDIRS, $this->maxRedirects); - curl_setopt($s, CURLOPT_RETURNTRANSFER, true); - curl_setopt($s, CURLOPT_FOLLOWLOCATION, $this->followLocation); - - if ( ! empty($this->cookieFileLocation) && file_exists($this->cookieFileLocation)) { - curl_setopt($s, CURLOPT_COOKIEJAR, $this->cookieFileLocation); - curl_setopt($s, CURLOPT_COOKIEFILE, $this->cookieFileLocation); - } - - if ( ! empty($this->sslVersion)) { - curl_setopt($s, CURLOPT_SSLVERSION, $this->sslVersion); - } - - if ($this->disableSslVerifyHost === true) { - curl_setopt($s, CURLOPT_SSL_VERIFYHOST, 0); - } - - if ($this->disableSslVerifyPeer === true) { - curl_setopt($s, CURLOPT_SSL_VERIFYPEER, 0); - } - - if ($this->sslVerifyHost === true) { - curl_setopt($s, CURLOPT_SSL_VERIFYHOST, 2); - } - - if ($this->sslVerifyPeer === true && file_exists($this->sslCaInfoFile)) { - curl_setopt($s, CURLOPT_SSL_VERIFYPEER, true); - curl_setopt($s, CURLOPT_CAINFO, $this->sslCaInfoFile); - } - - curl_setopt($s, CURLINFO_HEADER_OUT, $this->headerOut); - curl_setopt($s, CURLOPT_FILETIME, 1); - - if ($this->authentication === 1) { - curl_setopt($s, CURLOPT_USERPWD, $this->authUsername . ':' . $this->authPassword); - } - - if ($this->post || $this->json || $this->xml) { - curl_setopt($s, CURLOPT_POST, true); - curl_setopt($s, CURLOPT_POSTFIELDS, $this->postFields); - } - - if ($this->includeHeader) { - curl_setopt($s, CURLOPT_HEADER, true); - } - - if ($this->noBody) { - curl_setopt($s, CURLOPT_NOBODY, true); - } - - if ($this->binaryTransfer) { - curl_setopt($s, CURLOPT_BINARYTRANSFER, true); - } - - curl_setopt($s, CURLOPT_USERAGENT, $this->userAgent); - curl_setopt($s, CURLOPT_REFERER, $this->referer); - curl_setopt_array($s, $this->userOptions); - - $this->webpage = curl_exec($s); - $this->status = curl_getinfo($s); - $this->error = curl_error($s); - - if ($this->error) { - $this->isError = true; - } - - $this->session = $s; - - return $this; - } - - public function closeCurl() - { - curl_close($this->session); - } - - public function getHttpStatus() - { - return $this->status; - } - - public function getResponse() - { - return $this->webpage; - } - - public function isError() - { - return $this->isError; - } - - public function getError() - { - return $this->error; - } - - public function __toString() - { - return $this->webpage; - } + protected $userAgent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36'; + protected $url; + protected $data; + protected $followLocation; + protected $timeout; + protected $maxRedirects; + protected $cookieFileLocation; + protected $disableSslVerifyHost; + protected $disableSslVerifyPeer; + protected $sslVerifyHost; + protected $sslVerifyPeer; + protected $sslCaInfoFile; + protected $sslVersion; + protected $xml; + protected $json; + protected $post; + protected $postFields; + protected $referer = ""; + protected $session; + protected $webpage; + protected $headers; + protected $headerOut; + protected $includeHeader; + protected $noBody; + protected $status; + protected $isError = false; + protected $error; + protected $binaryTransfer; + protected $userOptions; + protected $authentication = 0; + protected $authUsername = ''; + protected $authPassword = ''; + + /** + * SimpleCurl constructor. + * + * @param string $url + * @param array $options + * + * @author : 713uk13m + * @copyright: 713uk13m + */ + public function __construct($url = '', $options = array()) + { + $this->url = $url; + $this->followLocation = true; + $this->timeout = 180; + $this->maxRedirects = 10; + $this->noBody = false; + $this->includeHeader = false; + $this->headerOut = true; + $this->binaryTransfer = false; + $this->headers[] = "Connection: keep-alive"; + $this->headers[] = "Keep-Alive: 300"; + $this->headers[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7"; + $this->headers[] = "Accept-Language: en-us,en;q=0.5"; + $this->userOptions = $options; + } + + public function setBinaryTransfer($binaryTransfer = true) + { + $this->binaryTransfer = $binaryTransfer; + + return $this; + } + + public function setCookieFileLocation($cookieFileLocation = '') + { + $this->cookieFileLocation = $cookieFileLocation; + + return $this; + } + + public function useAuth($use) + { + $this->authentication = 0; + if ($use === true) { + $this->authentication = 1; + } + + return $this; + } + + public function setAuthUsername($authUsername) + { + $this->authUsername = $authUsername; + + return $this; + } + + public function setAuthPassword($authPassword) + { + $this->authPassword = $authPassword; + + return $this; + } + + public function setUrl($url) + { + $this->url = $url; + + return $this; + } + + public function setReferer($referer) + { + $this->referer = $referer; + + return $this; + } + + public function setHeader($header) + { + $this->headers[] = $header; + + return $this; + } + + public function includeHeader($includeHeader = true) + { + $this->includeHeader = $includeHeader; + + return $this; + } + + public function setPost($postFields) + { + if (is_array($postFields)) { + $postFields = http_build_query($postFields); + } + $this->post = true; + $this->postFields = $postFields; + + return $this; + } + + public function setJson($postFields) + { + if (is_array($postFields) || is_object($postFields)) { + $postFields = json_encode($postFields); + } + $this->json = true; + $this->postFields = $postFields; + $this->headers[] = "Accept: application/json; charset=utf-8"; + $this->headers[] = "Content-Type: application/json; charset=utf-8"; + + return $this; + } + + public function setXml($xmlData) + { + $this->xml = true; + $this->postFields = $xmlData; + $this->headers[] = "Accept: text/xml; charset=utf-8"; + $this->headers[] = "Content-Type: text/xml; charset=utf-8"; + + return $this; + } + + public function setData($data) + { + $this->data = $data; + + return $this; + } + + public function setUserAgent($userAgent) + { + $this->userAgent = $userAgent; + + return $this; + } + + /** + * @see https://curl.se/libcurl/c/CURLOPT_SSL_VERIFYHOST.html + */ + public function disabledSslVerifyHost() + { + $this->disableSslVerifyHost = true; + + return $this; + } + + /** + * @see https://curl.se/libcurl/c/CURLOPT_SSL_VERIFYPEER.html + * @see https://www.saotn.org/dont-turn-off-curlopt_ssl_verifypeer-fix-php-configuration/#gsc.tab=0 + */ + public function disabledSslVerifyPeer() + { + $this->disableSslVerifyPeer = true; + + return $this; + } + + public function enabledSslVerifyPeer($certificateFile) + { + $this->sslVerifyPeer = true; + $this->sslCaInfoFile = $certificateFile; + + return $this; + } + + /** + * @see https://www.php.net/manual/en/function.curl-setopt.php + */ + public function setSslVersion($sslVersion) + { + $this->sslVersion = $sslVersion; + + return $this; + } + + public function createCurl($url = null) + { + if ($url !== null) { + $this->url = $url; + } + + $s = curl_init(); + curl_setopt($s, CURLOPT_URL, $this->url); + curl_setopt($s, CURLOPT_HTTPHEADER, $this->headers); + curl_setopt($s, CURLOPT_TIMEOUT, $this->timeout); + curl_setopt($s, CURLOPT_MAXREDIRS, $this->maxRedirects); + curl_setopt($s, CURLOPT_RETURNTRANSFER, true); + curl_setopt($s, CURLOPT_FOLLOWLOCATION, $this->followLocation); + + if (!empty($this->cookieFileLocation) && file_exists($this->cookieFileLocation)) { + curl_setopt($s, CURLOPT_COOKIEJAR, $this->cookieFileLocation); + curl_setopt($s, CURLOPT_COOKIEFILE, $this->cookieFileLocation); + } + + if (!empty($this->sslVersion)) { + curl_setopt($s, CURLOPT_SSLVERSION, $this->sslVersion); + } + + if ($this->disableSslVerifyHost === true) { + curl_setopt($s, CURLOPT_SSL_VERIFYHOST, 0); + } + + if ($this->disableSslVerifyPeer === true) { + curl_setopt($s, CURLOPT_SSL_VERIFYPEER, 0); + } + + if ($this->sslVerifyHost === true) { + curl_setopt($s, CURLOPT_SSL_VERIFYHOST, 2); + } + + if ($this->sslVerifyPeer === true && file_exists($this->sslCaInfoFile)) { + curl_setopt($s, CURLOPT_SSL_VERIFYPEER, true); + curl_setopt($s, CURLOPT_CAINFO, $this->sslCaInfoFile); + } + + curl_setopt($s, CURLINFO_HEADER_OUT, $this->headerOut); + curl_setopt($s, CURLOPT_FILETIME, 1); + + if ($this->authentication === 1) { + curl_setopt($s, CURLOPT_USERPWD, $this->authUsername . ':' . $this->authPassword); + } + + if ($this->post || $this->json || $this->xml) { + curl_setopt($s, CURLOPT_POST, true); + curl_setopt($s, CURLOPT_POSTFIELDS, $this->postFields); + } + + if ($this->includeHeader) { + curl_setopt($s, CURLOPT_HEADER, true); + } + + if ($this->noBody) { + curl_setopt($s, CURLOPT_NOBODY, true); + } + + if ($this->binaryTransfer) { + curl_setopt($s, CURLOPT_BINARYTRANSFER, true); + } + + curl_setopt($s, CURLOPT_USERAGENT, $this->userAgent); + curl_setopt($s, CURLOPT_REFERER, $this->referer); + curl_setopt_array($s, $this->userOptions); + + $this->webpage = curl_exec($s); + $this->status = curl_getinfo($s); + $this->error = curl_error($s); + + if ($this->error) { + $this->isError = true; + } + + $this->session = $s; + + return $this; + } + + public function closeCurl() + { + curl_close($this->session); + } + + public function getHttpStatus() + { + return $this->status; + } + + public function getResponse() + { + return $this->webpage; + } + + public function isError() + { + return $this->isError; + } + + public function getError() + { + return $this->error; + } + + public function __toString() + { + return $this->webpage; + } } diff --git a/src/SimpleElasticsearch.php b/src/SimpleElasticsearch.php index 70a3312..4228fd8 100644 --- a/src/SimpleElasticsearch.php +++ b/src/SimpleElasticsearch.php @@ -21,512 +21,512 @@ */ class SimpleElasticsearch extends BaseHelper { - protected $host = 'http://localhost'; - protected $port = 9200; - - /** - * Function setHost - * - * @param string $host - * - * @author : 713uk13m - * @copyright: 713uk13m - */ - public function setHost($host) - { - $this->host = $host; - - return $this; - } - - /** - * Function Host - * - * @return string - * - * @author : 713uk13m - * @copyright: 713uk13m - */ - public function getHost() - { - return $this->host; - } - - /** - * Function setPort - * - * @param int $port - * - * @author : 713uk13m - * @copyright: 713uk13m - */ - public function setPort($port) - { - $this->port = $port; - - return $this; - } - - /** - * Function Port - * - * @return int - * - * @author : 713uk13m - * @copyright: 713uk13m - */ - public function getPort() - { - return $this->port; - } - - public function complexSearch( - $string = null, - $fields = array("_all"), - $sort = array(), - $index = null, - $page = 1, - $limit = 10, - $fullResponse = false, - $extraParams = null - ) { - try { - $elasticHost = $this->host; - $elasticPort = $this->port; - - $error_msg = $httpCode = null; - - if (empty($index) || empty($string)) { - return false; - } - - $query_string = array( - "query" => array( - "multi_match" => array( - "query" => $string, - "fields" => $fields - ) - ), - "size" => $limit - ); - if ( ! empty($sort) && is_array($sort)) { - $query_string['sort'] = $sort; - } - - $page && $query_string['from'] = ($page - 1) * $limit; - - $endpoint = $elasticHost . ':' . $elasticPort . '/' . $index . "/_search"; - - if (is_array($extraParams)) { - $endpoint .= '?' . http_build_query($extraParams); - } - - $curl = curl_init(); - - curl_setopt_array($curl, array( - CURLOPT_URL => $endpoint, - CURLOPT_RETURNTRANSFER => true, - CURLOPT_ENCODING => '', - CURLOPT_MAXREDIRS => 10, - CURLOPT_TIMEOUT => 0, - CURLOPT_FOLLOWLOCATION => true, - CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, - CURLOPT_CUSTOMREQUEST => 'GET', - CURLOPT_POSTFIELDS => json_encode($query_string), - CURLOPT_HTTPHEADER => array( - 'Content-Type: application/json' - ), - )); - $response = curl_exec($curl); - // echo PHP_EOL . ' GET Request - ' . $elasticHost . ':' . $elasticPort . '/' . $index . '/_search |-> ' . json_encode($query_string, JSON_PRETTY_PRINT) . ' | -> Response: ' . $response . PHP_EOL; - - - if (curl_errno($curl)) { - $error_msg = curl_error($curl); - $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); - } - - curl_close($curl); - if ($fullResponse === true) { - return self::fullDataResponse($response, $page, $limit, $error_msg, $httpCode); - } - - // đoạn này đang resize lại để lấy bản ghi đầu tiên - return self::resolutionResponse($response, $page, $limit, $error_msg, $httpCode); - } catch (Exception $e) { - return [ - 'statusCode' => 0, - 'errors' => "Co loi khi tim kiem san pham, kiem tra lai he thong!" - ]; - } - } - - public function filterSearch( - $index, - $query_string, - $page = 1, - $limit = 10, - $fullResponse = false, - $extraParams = null - ) { - try { - $elasticHost = $this->host; - $elasticPort = $this->port; - $error_msg = $httpCode = null; - if (empty($index) || empty($query_string)) { - return false; - } - $page && $query_string['from'] = ($page - 1) * $limit; - $endpoint = $elasticHost . ':' . $elasticPort . '/' . $index . "/_search"; - if (is_array($extraParams)) { - $endpoint .= '?' . http_build_query($extraParams); - } - $curl = curl_init(); - curl_setopt_array($curl, array( - CURLOPT_URL => $endpoint, - CURLOPT_RETURNTRANSFER => true, - CURLOPT_ENCODING => '', - CURLOPT_MAXREDIRS => 10, - CURLOPT_TIMEOUT => 0, - CURLOPT_FOLLOWLOCATION => true, - CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, - CURLOPT_CUSTOMREQUEST => 'GET', - CURLOPT_POSTFIELDS => json_encode($query_string), - CURLOPT_HTTPHEADER => array( - 'Content-Type: application/json' - ), - )); - $response = curl_exec($curl); - // echo PHP_EOL . ' GET Request - ' . $elasticHost . ':' . $elasticPort . '/' . $index . '/_search |-> ' . json_encode($query_string, JSON_PRETTY_PRINT) . ' | -> Response: ' . $response . PHP_EOL; - - - if (curl_errno($curl)) { - $error_msg = curl_error($curl); - $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); - } - - curl_close($curl); - if ($fullResponse === true) { - return self::fullDataResponse($response, $page, $limit, $error_msg, $httpCode); - } - - // đoạn này đang resize lại để lấy bản ghi đầu tiên - return self::resolutionResponse($response, $page, $limit, $error_msg, $httpCode); - } catch (Exception $exception) { - return [ - 'statusCode' => 0, - 'errors' => "Co loi khi tim kiem san pham, kiem tra lai he thong!" - ]; - } - } - - public static function resolutionResponse($data, $page = 1, $limit = 10, $error_msg = null, $httpCode = null) - { - if ($error_msg) { - $statusCode = $httpCode !== null ? 0 : $httpCode; - - return array( - 'statusCode' => $statusCode, - 'errors' => $error_msg - ); - } - - if ( ! $data) { - return false; - } - - $response = json_decode($data, false); - - $total = isset($response->hits->total->value) ? $response->hits->total->value : 0; - if (isset($response->hits->hits[0]->_source) && ! empty($response->hits->hits[0]->_source)) { - $data = $response->hits->hits[0]->_source; - } else { - $data = array(); - } - - return array( - 'total' => $total, - 'current_page' => $page, - 'per_page' => $limit, - 'fully_data' => $response, - 'data' => $data - ); - } - - public static function fullDataResponse($data, $page = 1, $limit = 10, $error_msg = null, $httpCode = null) - { - if ($error_msg) { - $statusCode = $httpCode !== null ? 0 : $httpCode; - - return array( - 'statusCode' => $statusCode, - 'errors' => $error_msg - ); - } - - if ( ! $data) { - return false; - } - - $response = json_decode($data, false); - $total = isset($response->hits->total->value) ? $response->hits->total->value : 0; - if (isset($response->hits->hits) && ! empty($response->hits->hits)) { - $data = $response->hits->hits; - } else { - $data = array(); - } - - return array( - 'total' => $total, - 'current_page' => $page, - 'per_page' => $limit, - 'data' => $data - ); - } - - /** - * @throws \nguyenanhung\CodeIgniter\BasicHelper\HelperException - */ - public function syncDataElasticsearch($data, $action, $id, $index) - { - try { - $elasticHost = $this->host; - $elasticPort = $this->port; - - if (empty($index) || empty($action)) { - return false; - } - - - if ($action !== 'delete' && empty($data)) { - return false; - } - if ($action === 'create' && ! ($data instanceof Model)) { - return false; - } - - - $url = $elasticHost . ':' . $elasticPort . '/' . $index . '/_doc/' . $id; - $data_config_url = array( - CURLOPT_URL => $url, - CURLOPT_RETURNTRANSFER => true, - CURLOPT_ENCODING => '', - CURLOPT_MAXREDIRS => 10, - CURLOPT_TIMEOUT => 0, - CURLOPT_FOLLOWLOCATION => true, - CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, - CURLOPT_CUSTOMREQUEST => 'DELETE', - CURLOPT_HTTPHEADER => array( - 'Content-Type: application/json' - ) - ); - - switch ($action) { - case 'delete': - if ( ! $id) { - return false; - } - $data_config_url[CURLOPT_URL] = $url; - $data_config_url[CURLOPT_CUSTOMREQUEST] = 'DELETE'; - - break; - case 'update_or_create': - $data = is_array($data) ? $data : (array)$data; - if ( ! $id) { - return false; - } - if ($data === null) { - return false; - } - $data_config_url[CURLOPT_URL] = $url; - $data_config_url[CURLOPT_CUSTOMREQUEST] = 'POST'; - $data_config_url[CURLOPT_POSTFIELDS] = json_encode($data); - break; - default: - return false; - } - - - $curl = curl_init(); - - curl_setopt_array($curl, $data_config_url); - $response = curl_exec($curl); - - echo PHP_EOL . $data_config_url[CURLOPT_CUSTOMREQUEST] . ' - ' . $url . ' |-> ' . json_encode( - $data, - JSON_PRETTY_PRINT - ) . ' | -> Response: ' . $response . PHP_EOL; - - if (curl_errno($curl)) { - $error_msg = curl_error($curl); - } - curl_close($curl); - - if (isset($error_msg)) { - // echo 'error sync :' . $id . '__:' . json_encode($error_msg) . 'id :' . $index . 'action :' . $action . PHP_EOL; - Log::info( - 'error sync :' . $id . '__:' . json_encode($error_msg) . 'id :' . $index . 'action :' . $action - ); - } - - return true; - } catch (Exception $e) { - // echo 'error sync :' . $id . '__:' . $e->getMessage() . 'id :' . $index . 'action :' . $action . PHP_EOL; - Log::info('error sync :' . $id . '__:' . $e->getMessage() . 'id :' . $index . 'action :' . $action); - // echo $e->getTraceAsString(); - throw new HelperException($e->getMessage()); - } - } - - /** - * @throws \nguyenanhung\CodeIgniter\BasicHelper\HelperException - */ - public static function createIndexElasticsearch($index, $listFields, $specialFields) - { - try { - $elasticHost = env('ELASTICSEARCH_HOST', self::DEFAULT_ELASTICSEARCH_HOST); - $elasticPort = env('ELASTICSEARCH_PORT', self::DEFAULT_ELASTICSEARCH_PORT); - - $settings = array( - 'number_of_shards' => 2, - 'number_of_replicas' => 1, - 'analysis' => array( - 'char_filter' => array( - 'replace' => array( - 'type' => 'mapping', - 'mappings' => array( - '&=> and ' - ) - ) - ), - 'filter' => array( - 'word_delimiter' => array( - 'type' => 'word_delimiter', - 'split_on_numerics' => false, - 'split_on_case_change' => true, - 'generate_word_parts' => true, - 'generate_number_parts' => true, - 'catenate_all' => true, - 'preserve_original' => true, - 'catenate_numbers' => true, - ) - ), - 'analyzer' => array( - 'default' => array( - 'type' => 'custom', - 'char_filter' => array( - 'html_strip', - 'replace', - ), - 'tokenizer' => 'whitespace', - 'filter' => array( - 'lowercase', - 'word_delimiter', - ), - ), - 'my_analyzer' => array( - 'type' => 'custom', - 'tokenizer' => 'standard', - 'filter' => array( - 'lowercase' - ) - ), - "my_email_analyzer" => array( - "type" => "custom", - "tokenizer" => "uax_url_email", - 'filter' => array( - 'lowercase', - 'stop', - ), - ) - ) - ) - ); - - $data = array(); - $data['settings'] = $settings; - $data['mappings'] = array(); - $data['mappings']['properties'] = array(); - - foreach ($listFields as $field) { - if ($field === '_id') { - $field = 'id'; - } - if (array_key_exists($field, $specialFields)) { - $data['mappings']['properties'][$field] = $specialFields[$field]; - } else { - $data['mappings']['properties'][$field] = array( - 'type' => 'text', - 'analyzer' => 'my_analyzer' - ); - } - } - $url = $elasticHost . ':' . $elasticPort . '/' . $index . '?pretty'; - $data_config_url = array( - CURLOPT_URL => $url, - CURLOPT_RETURNTRANSFER => true, - CURLOPT_ENCODING => '', - CURLOPT_MAXREDIRS => 10, - CURLOPT_TIMEOUT => 0, - CURLOPT_FOLLOWLOCATION => true, - CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, - CURLOPT_CUSTOMREQUEST => 'PUT', - CURLOPT_POSTFIELDS => json_encode($data), - CURLOPT_HTTPHEADER => array( - 'Content-Type: application/json' - ), - ); - - $curl = curl_init(); - - curl_setopt_array($curl, $data_config_url); - $response = curl_exec($curl); - - echo PHP_EOL . $data_config_url[CURLOPT_CUSTOMREQUEST] . ' - ' . $url . ' |-> ' . json_encode( - $data, - JSON_PRETTY_PRINT - ) . ' | -> Response: ' . $response . PHP_EOL; - - if (curl_errno($curl)) { - $error_msg = curl_error($curl); - } - curl_close($curl); - - if (isset($error_msg)) { - // Log::info('error sync :' . $index . '__:' . json_encode($error_msg)); - } - - return true; - } catch (Exception $e) { - // echo 'error sync :' . $id . '__:' . $e->getMessage() . 'id :' . $index . 'action :' . $action . PHP_EOL; - // echo $e->getTraceAsString(); - throw new HelperException($e->getMessage()); - } - } - - public static function preparePaging($result, $currentPage, $pageUrl) - { - if ($result === false || isset($result['errors'])) { - return $result; - } - $nextPage = $currentPage + 1; - $perPage = isset($result['per_page']) ? $result['per_page'] : 0; - $total = isset($result['total']) ? $result['total'] : 0; - $from = ($currentPage - 1) * $perPage; - $to = ($from - 1) + $perPage; - $lastPage = round($total / $perPage); - - return array( - 'current_page' => $currentPage, - "first_page_url" => $pageUrl . '?' . http_build_query(array('page' => 1)), - "from" => $from, - "last_page" => $lastPage, - "last_page_url" => $pageUrl . '?' . http_build_query(array('page' => $lastPage)), - "next_page_url" => $pageUrl . '?' . http_build_query(array('page' => $nextPage)), - "per_page" => $perPage, - "to" => $to, - "total" => $total, - "data" => isset($result['data']) ? $result['data'] : array() - ); - } + protected $host = 'http://localhost'; + protected $port = 9200; + + /** + * Function setHost + * + * @param string $host + * + * @author : 713uk13m + * @copyright: 713uk13m + */ + public function setHost($host) + { + $this->host = $host; + + return $this; + } + + /** + * Function Host + * + * @return string + * + * @author : 713uk13m + * @copyright: 713uk13m + */ + public function getHost() + { + return $this->host; + } + + /** + * Function setPort + * + * @param int $port + * + * @author : 713uk13m + * @copyright: 713uk13m + */ + public function setPort($port) + { + $this->port = $port; + + return $this; + } + + /** + * Function Port + * + * @return int + * + * @author : 713uk13m + * @copyright: 713uk13m + */ + public function getPort() + { + return $this->port; + } + + public function complexSearch( + $string = null, + $fields = array("_all"), + $sort = array(), + $index = null, + $page = 1, + $limit = 10, + $fullResponse = false, + $extraParams = null + ) { + try { + $elasticHost = $this->host; + $elasticPort = $this->port; + + $error_msg = $httpCode = null; + + if (empty($index) || empty($string)) { + return false; + } + + $query_string = array( + "query" => array( + "multi_match" => array( + "query" => $string, + "fields" => $fields + ) + ), + "size" => $limit + ); + if (!empty($sort) && is_array($sort)) { + $query_string['sort'] = $sort; + } + + $page && $query_string['from'] = ($page - 1) * $limit; + + $endpoint = $elasticHost . ':' . $elasticPort . '/' . $index . "/_search"; + + if (is_array($extraParams)) { + $endpoint .= '?' . http_build_query($extraParams); + } + + $curl = curl_init(); + + curl_setopt_array($curl, array( + CURLOPT_URL => $endpoint, + CURLOPT_RETURNTRANSFER => true, + CURLOPT_ENCODING => '', + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 0, + CURLOPT_FOLLOWLOCATION => true, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => 'GET', + CURLOPT_POSTFIELDS => json_encode($query_string), + CURLOPT_HTTPHEADER => array( + 'Content-Type: application/json' + ), + )); + $response = curl_exec($curl); + // echo PHP_EOL . ' GET Request - ' . $elasticHost . ':' . $elasticPort . '/' . $index . '/_search |-> ' . json_encode($query_string, JSON_PRETTY_PRINT) . ' | -> Response: ' . $response . PHP_EOL; + + + if (curl_errno($curl)) { + $error_msg = curl_error($curl); + $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); + } + + curl_close($curl); + if ($fullResponse === true) { + return self::fullDataResponse($response, $page, $limit, $error_msg, $httpCode); + } + + // đoạn này đang resize lại để lấy bản ghi đầu tiên + return self::resolutionResponse($response, $page, $limit, $error_msg, $httpCode); + } catch (Exception $e) { + return [ + 'statusCode' => 0, + 'errors' => "Co loi khi tim kiem san pham, kiem tra lai he thong!" + ]; + } + } + + public function filterSearch( + $index, + $query_string, + $page = 1, + $limit = 10, + $fullResponse = false, + $extraParams = null + ) { + try { + $elasticHost = $this->host; + $elasticPort = $this->port; + $error_msg = $httpCode = null; + if (empty($index) || empty($query_string)) { + return false; + } + $page && $query_string['from'] = ($page - 1) * $limit; + $endpoint = $elasticHost . ':' . $elasticPort . '/' . $index . "/_search"; + if (is_array($extraParams)) { + $endpoint .= '?' . http_build_query($extraParams); + } + $curl = curl_init(); + curl_setopt_array($curl, array( + CURLOPT_URL => $endpoint, + CURLOPT_RETURNTRANSFER => true, + CURLOPT_ENCODING => '', + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 0, + CURLOPT_FOLLOWLOCATION => true, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => 'GET', + CURLOPT_POSTFIELDS => json_encode($query_string), + CURLOPT_HTTPHEADER => array( + 'Content-Type: application/json' + ), + )); + $response = curl_exec($curl); + // echo PHP_EOL . ' GET Request - ' . $elasticHost . ':' . $elasticPort . '/' . $index . '/_search |-> ' . json_encode($query_string, JSON_PRETTY_PRINT) . ' | -> Response: ' . $response . PHP_EOL; + + + if (curl_errno($curl)) { + $error_msg = curl_error($curl); + $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); + } + + curl_close($curl); + if ($fullResponse === true) { + return self::fullDataResponse($response, $page, $limit, $error_msg, $httpCode); + } + + // đoạn này đang resize lại để lấy bản ghi đầu tiên + return self::resolutionResponse($response, $page, $limit, $error_msg, $httpCode); + } catch (Exception $exception) { + return [ + 'statusCode' => 0, + 'errors' => "Co loi khi tim kiem san pham, kiem tra lai he thong!" + ]; + } + } + + public static function resolutionResponse($data, $page = 1, $limit = 10, $error_msg = null, $httpCode = null) + { + if ($error_msg) { + $statusCode = $httpCode !== null ? 0 : $httpCode; + + return array( + 'statusCode' => $statusCode, + 'errors' => $error_msg + ); + } + + if (!$data) { + return false; + } + + $response = json_decode($data, false); + + $total = isset($response->hits->total->value) ? $response->hits->total->value : 0; + if (isset($response->hits->hits[0]->_source) && !empty($response->hits->hits[0]->_source)) { + $data = $response->hits->hits[0]->_source; + } else { + $data = array(); + } + + return array( + 'total' => $total, + 'current_page' => $page, + 'per_page' => $limit, + 'fully_data' => $response, + 'data' => $data + ); + } + + public static function fullDataResponse($data, $page = 1, $limit = 10, $error_msg = null, $httpCode = null) + { + if ($error_msg) { + $statusCode = $httpCode !== null ? 0 : $httpCode; + + return array( + 'statusCode' => $statusCode, + 'errors' => $error_msg + ); + } + + if (!$data) { + return false; + } + + $response = json_decode($data, false); + $total = isset($response->hits->total->value) ? $response->hits->total->value : 0; + if (isset($response->hits->hits) && !empty($response->hits->hits)) { + $data = $response->hits->hits; + } else { + $data = array(); + } + + return array( + 'total' => $total, + 'current_page' => $page, + 'per_page' => $limit, + 'data' => $data + ); + } + + /** + * @throws \nguyenanhung\CodeIgniter\BasicHelper\HelperException + */ + public function syncDataElasticsearch($data, $action, $id, $index) + { + try { + $elasticHost = $this->host; + $elasticPort = $this->port; + + if (empty($index) || empty($action)) { + return false; + } + + + if ($action !== 'delete' && empty($data)) { + return false; + } + if ($action === 'create' && !($data instanceof Model)) { + return false; + } + + + $url = $elasticHost . ':' . $elasticPort . '/' . $index . '/_doc/' . $id; + $data_config_url = array( + CURLOPT_URL => $url, + CURLOPT_RETURNTRANSFER => true, + CURLOPT_ENCODING => '', + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 0, + CURLOPT_FOLLOWLOCATION => true, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => 'DELETE', + CURLOPT_HTTPHEADER => array( + 'Content-Type: application/json' + ) + ); + + switch ($action) { + case 'delete': + if (!$id) { + return false; + } + $data_config_url[CURLOPT_URL] = $url; + $data_config_url[CURLOPT_CUSTOMREQUEST] = 'DELETE'; + + break; + case 'update_or_create': + $data = is_array($data) ? $data : (array)$data; + if (!$id) { + return false; + } + if ($data === null) { + return false; + } + $data_config_url[CURLOPT_URL] = $url; + $data_config_url[CURLOPT_CUSTOMREQUEST] = 'POST'; + $data_config_url[CURLOPT_POSTFIELDS] = json_encode($data); + break; + default: + return false; + } + + + $curl = curl_init(); + + curl_setopt_array($curl, $data_config_url); + $response = curl_exec($curl); + + echo PHP_EOL . $data_config_url[CURLOPT_CUSTOMREQUEST] . ' - ' . $url . ' |-> ' . json_encode( + $data, + JSON_PRETTY_PRINT + ) . ' | -> Response: ' . $response . PHP_EOL; + + if (curl_errno($curl)) { + $error_msg = curl_error($curl); + } + curl_close($curl); + + if (isset($error_msg)) { + // echo 'error sync :' . $id . '__:' . json_encode($error_msg) . 'id :' . $index . 'action :' . $action . PHP_EOL; + Log::info( + 'error sync :' . $id . '__:' . json_encode($error_msg) . 'id :' . $index . 'action :' . $action + ); + } + + return true; + } catch (Exception $e) { + // echo 'error sync :' . $id . '__:' . $e->getMessage() . 'id :' . $index . 'action :' . $action . PHP_EOL; + Log::info('error sync :' . $id . '__:' . $e->getMessage() . 'id :' . $index . 'action :' . $action); + // echo $e->getTraceAsString(); + throw new HelperException($e->getMessage()); + } + } + + /** + * @throws \nguyenanhung\CodeIgniter\BasicHelper\HelperException + */ + public static function createIndexElasticsearch($index, $listFields, $specialFields) + { + try { + $elasticHost = env('ELASTICSEARCH_HOST', self::DEFAULT_ELASTICSEARCH_HOST); + $elasticPort = env('ELASTICSEARCH_PORT', self::DEFAULT_ELASTICSEARCH_PORT); + + $settings = array( + 'number_of_shards' => 2, + 'number_of_replicas' => 1, + 'analysis' => array( + 'char_filter' => array( + 'replace' => array( + 'type' => 'mapping', + 'mappings' => array( + '&=> and ' + ) + ) + ), + 'filter' => array( + 'word_delimiter' => array( + 'type' => 'word_delimiter', + 'split_on_numerics' => false, + 'split_on_case_change' => true, + 'generate_word_parts' => true, + 'generate_number_parts' => true, + 'catenate_all' => true, + 'preserve_original' => true, + 'catenate_numbers' => true, + ) + ), + 'analyzer' => array( + 'default' => array( + 'type' => 'custom', + 'char_filter' => array( + 'html_strip', + 'replace', + ), + 'tokenizer' => 'whitespace', + 'filter' => array( + 'lowercase', + 'word_delimiter', + ), + ), + 'my_analyzer' => array( + 'type' => 'custom', + 'tokenizer' => 'standard', + 'filter' => array( + 'lowercase' + ) + ), + "my_email_analyzer" => array( + "type" => "custom", + "tokenizer" => "uax_url_email", + 'filter' => array( + 'lowercase', + 'stop', + ), + ) + ) + ) + ); + + $data = array(); + $data['settings'] = $settings; + $data['mappings'] = array(); + $data['mappings']['properties'] = array(); + + foreach ($listFields as $field) { + if ($field === '_id') { + $field = 'id'; + } + if (array_key_exists($field, $specialFields)) { + $data['mappings']['properties'][$field] = $specialFields[$field]; + } else { + $data['mappings']['properties'][$field] = array( + 'type' => 'text', + 'analyzer' => 'my_analyzer' + ); + } + } + $url = $elasticHost . ':' . $elasticPort . '/' . $index . '?pretty'; + $data_config_url = array( + CURLOPT_URL => $url, + CURLOPT_RETURNTRANSFER => true, + CURLOPT_ENCODING => '', + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 0, + CURLOPT_FOLLOWLOCATION => true, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => 'PUT', + CURLOPT_POSTFIELDS => json_encode($data), + CURLOPT_HTTPHEADER => array( + 'Content-Type: application/json' + ), + ); + + $curl = curl_init(); + + curl_setopt_array($curl, $data_config_url); + $response = curl_exec($curl); + + echo PHP_EOL . $data_config_url[CURLOPT_CUSTOMREQUEST] . ' - ' . $url . ' |-> ' . json_encode( + $data, + JSON_PRETTY_PRINT + ) . ' | -> Response: ' . $response . PHP_EOL; + + if (curl_errno($curl)) { + $error_msg = curl_error($curl); + } + curl_close($curl); + + if (isset($error_msg)) { + // Log::info('error sync :' . $index . '__:' . json_encode($error_msg)); + } + + return true; + } catch (Exception $e) { + // echo 'error sync :' . $id . '__:' . $e->getMessage() . 'id :' . $index . 'action :' . $action . PHP_EOL; + // echo $e->getTraceAsString(); + throw new HelperException($e->getMessage()); + } + } + + public static function preparePaging($result, $currentPage, $pageUrl) + { + if ($result === false || isset($result['errors'])) { + return $result; + } + $nextPage = $currentPage + 1; + $perPage = isset($result['per_page']) ? $result['per_page'] : 0; + $total = isset($result['total']) ? $result['total'] : 0; + $from = ($currentPage - 1) * $perPage; + $to = ($from - 1) + $perPage; + $lastPage = round($total / $perPage); + + return array( + 'current_page' => $currentPage, + "first_page_url" => $pageUrl . '?' . http_build_query(array('page' => 1)), + "from" => $from, + "last_page" => $lastPage, + "last_page_url" => $pageUrl . '?' . http_build_query(array('page' => $lastPage)), + "next_page_url" => $pageUrl . '?' . http_build_query(array('page' => $nextPage)), + "per_page" => $perPage, + "to" => $to, + "total" => $total, + "data" => isset($result['data']) ? $result['data'] : array() + ); + } } diff --git a/src/SimpleParseOpenGraph.php b/src/SimpleParseOpenGraph.php index 62b5ddf..fd9f1cc 100644 --- a/src/SimpleParseOpenGraph.php +++ b/src/SimpleParseOpenGraph.php @@ -12,232 +12,232 @@ class SimpleParseOpenGraph extends BaseHelper implements \Iterator { - /** - * There are base schema's based on type, this is just - * a map so that the schema can be obtained - * - */ - public static $TYPES = array( - 'activity' => array('activity', 'sport'), - 'business' => array('bar', 'company', 'cafe', 'hotel', 'restaurant'), - 'group' => array('cause', 'sports_league', 'sports_team'), - 'organization' => array('band', 'government', 'non_profit', 'school', 'university'), - 'person' => array('actor', 'athlete', 'author', 'director', 'musician', 'politician', 'public_figure'), - 'place' => array('city', 'country', 'landmark', 'state_province'), - 'product' => array('album', 'book', 'drink', 'food', 'game', 'movie', 'product', 'song', 'tv_show'), - 'website' => array('blog', 'website'), - ); - - /** - * Holds all the Open Graph values we've parsed from a page - * - */ - private $_values = array(); - - /** - * Fetches a URI and parses it for Open Graph data, returns - * false on error. - * - * @param mixed $URI URI to page to parse for Open Graph data - * @return SimpleParseOpenGraph|bool - */ - static public function fetch($URI) - { - $curl = curl_init($URI); - - curl_setopt($curl, CURLOPT_FAILONERROR, true); - curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); - curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); - curl_setopt($curl, CURLOPT_TIMEOUT, 15); - curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); - curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); - if (isset($_SERVER['HTTP_USER_AGENT'])) { - curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); - } else { - curl_setopt( - $curl, - CURLOPT_USERAGENT, - "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36" - ); - } - - - $response = curl_exec($curl); - - curl_close($curl); - - if ( ! empty($response)) { - return self::_parse($response); - } - - return false; - } - - /** - * Parses HTML and extracts Open Graph data, this assumes - * the document is at least well formed. - * - * @param mixed $HTML HTML to parse - * @return SimpleParseOpenGraph - */ - static private function _parse($HTML) - { - $old_libxml_error = libxml_use_internal_errors(true); - - $doc = new \DOMDocument(); - $doc->loadHTML($HTML); - - libxml_use_internal_errors($old_libxml_error); - - $tags = $doc->getElementsByTagName('meta'); - if ( ! $tags || $tags->length === 0) { - return false; - } - - $page = new self(); - - $nonOgDescription = null; - - foreach ($tags as $tag) { - if ($tag->hasAttribute('property') && - mb_strpos($tag->getAttribute('property'), 'og:') === 0) { - $key = strtr(mb_substr($tag->getAttribute('property'), 3), '-', '_'); - $page->_values[$key] = $tag->getAttribute('content'); - } - - //Added this if loop to retrieve description values from sites like the New York Times who have malformed it. - if ($tag->hasAttribute('value') && $tag->hasAttribute('property') && - mb_strpos($tag->getAttribute('property'), 'og:') === 0) { - $key = strtr(mb_substr($tag->getAttribute('property'), 3), '-', '_'); - $page->_values[$key] = $tag->getAttribute('value'); - } - //Based on modifications at https://github.com/bashofmann/opengraph/blob/master/src/OpenGraph/OpenGraph.php - if ($tag->hasAttribute('name') && $tag->getAttribute('name') === 'description') { - $nonOgDescription = $tag->getAttribute('content'); - } - } - //Based on modifications at https://github.com/bashofmann/opengraph/blob/master/src/OpenGraph/OpenGraph.php - if ( ! isset($page->_values['title'])) { - $titles = $doc->getElementsByTagName('title'); - if ($titles->length > 0) { - $page->_values['title'] = $titles->item(0)->textContent; - } - } - if ( ! isset($page->_values['description']) && $nonOgDescription) { - $page->_values['description'] = $nonOgDescription; - } - - //Fallback to use image_src if ogp::image isn't set. - if ( ! isset($page->values['image'])) { - $domxpath = new \DOMXPath($doc); - $elements = $domxpath->query("//link[@rel='image_src']"); - - if ($elements->length > 0) { - $domattr = $elements->item(0)->attributes->getNamedItem('href'); - if ($domattr) { - $page->_values['image'] = $domattr->value; - $page->_values['image_src'] = $domattr->value; - } - } - } - - if (empty($page->_values)) { - return false; - } - - return $page; - } - - /** - * Helper method to access attributes directly - * Example: - * $graph->title - * - * @param mixed $key Key to fetch from the lookup - */ - public function __get($key) - { - if (array_key_exists($key, $this->_values)) { - return $this->_values[$key]; - } - - if ($key === 'schema') { - foreach (self::$TYPES as $schema => $types) { - if (array_search($this->_values['type'], $types)) { - return $schema; - } - } - } - } - - /** - * Return all the keys found on the page - * - * @return array - */ - public function keys() - { - return array_keys($this->_values); - } - - /** - * Helper method to check an attribute exists - * - * @param mixed $key - */ - public function __isset($key) - { - return array_key_exists($key, $this->_values); - } - - /** - * Will return true if the page has location data embedded - * - * @return boolean Check if the page has location data - */ - public function hasLocation() - { - if (array_key_exists('latitude', $this->_values) && array_key_exists('longitude', $this->_values)) { - return true; - } - - $address_keys = array('street_address', 'locality', 'region', 'postal_code', 'country_name'); - $valid_address = true; - foreach ($address_keys as $key) { - $valid_address = ($valid_address && array_key_exists($key, $this->_values)); - } - return $valid_address; - } - - /** - * Iterator code - */ - private $_position = 0; - - public function rewind() - { - reset($this->_values); - $this->_position = 0; - } - - public function current() - { - return current($this->_values); - } - - public function key() - { - return key($this->_values); - } - - public function next() - { - next($this->_values); - ++$this->_position; - } - - public function valid() - { - return $this->_position < sizeof($this->_values); - } + /** + * There are base schema's based on type, this is just + * a map so that the schema can be obtained + * + */ + public static $TYPES = array( + 'activity' => array('activity', 'sport'), + 'business' => array('bar', 'company', 'cafe', 'hotel', 'restaurant'), + 'group' => array('cause', 'sports_league', 'sports_team'), + 'organization' => array('band', 'government', 'non_profit', 'school', 'university'), + 'person' => array('actor', 'athlete', 'author', 'director', 'musician', 'politician', 'public_figure'), + 'place' => array('city', 'country', 'landmark', 'state_province'), + 'product' => array('album', 'book', 'drink', 'food', 'game', 'movie', 'product', 'song', 'tv_show'), + 'website' => array('blog', 'website'), + ); + + /** + * Holds all the Open Graph values we've parsed from a page + * + */ + private $_values = array(); + + /** + * Fetches a URI and parses it for Open Graph data, returns + * false on error. + * + * @param mixed $URI URI to page to parse for Open Graph data + * @return SimpleParseOpenGraph|bool + */ + static public function fetch($URI) + { + $curl = curl_init($URI); + + curl_setopt($curl, CURLOPT_FAILONERROR, true); + curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curl, CURLOPT_TIMEOUT, 15); + curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); + curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); + if (isset($_SERVER['HTTP_USER_AGENT'])) { + curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); + } else { + curl_setopt( + $curl, + CURLOPT_USERAGENT, + "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36" + ); + } + + + $response = curl_exec($curl); + + curl_close($curl); + + if (!empty($response)) { + return self::_parse($response); + } + + return false; + } + + /** + * Parses HTML and extracts Open Graph data, this assumes + * the document is at least well formed. + * + * @param mixed $HTML HTML to parse + * @return SimpleParseOpenGraph + */ + static private function _parse($HTML) + { + $old_libxml_error = libxml_use_internal_errors(true); + + $doc = new \DOMDocument(); + $doc->loadHTML($HTML); + + libxml_use_internal_errors($old_libxml_error); + + $tags = $doc->getElementsByTagName('meta'); + if (!$tags || $tags->length === 0) { + return false; + } + + $page = new self(); + + $nonOgDescription = null; + + foreach ($tags as $tag) { + if ($tag->hasAttribute('property') && + mb_strpos($tag->getAttribute('property'), 'og:') === 0) { + $key = strtr(mb_substr($tag->getAttribute('property'), 3), '-', '_'); + $page->_values[$key] = $tag->getAttribute('content'); + } + + //Added this if loop to retrieve description values from sites like the New York Times who have malformed it. + if ($tag->hasAttribute('value') && $tag->hasAttribute('property') && + mb_strpos($tag->getAttribute('property'), 'og:') === 0) { + $key = strtr(mb_substr($tag->getAttribute('property'), 3), '-', '_'); + $page->_values[$key] = $tag->getAttribute('value'); + } + //Based on modifications at https://github.com/bashofmann/opengraph/blob/master/src/OpenGraph/OpenGraph.php + if ($tag->hasAttribute('name') && $tag->getAttribute('name') === 'description') { + $nonOgDescription = $tag->getAttribute('content'); + } + } + //Based on modifications at https://github.com/bashofmann/opengraph/blob/master/src/OpenGraph/OpenGraph.php + if (!isset($page->_values['title'])) { + $titles = $doc->getElementsByTagName('title'); + if ($titles->length > 0) { + $page->_values['title'] = $titles->item(0)->textContent; + } + } + if (!isset($page->_values['description']) && $nonOgDescription) { + $page->_values['description'] = $nonOgDescription; + } + + //Fallback to use image_src if ogp::image isn't set. + if (!isset($page->values['image'])) { + $domxpath = new \DOMXPath($doc); + $elements = $domxpath->query("//link[@rel='image_src']"); + + if ($elements->length > 0) { + $domattr = $elements->item(0)->attributes->getNamedItem('href'); + if ($domattr) { + $page->_values['image'] = $domattr->value; + $page->_values['image_src'] = $domattr->value; + } + } + } + + if (empty($page->_values)) { + return false; + } + + return $page; + } + + /** + * Helper method to access attributes directly + * Example: + * $graph->title + * + * @param mixed $key Key to fetch from the lookup + */ + public function __get($key) + { + if (array_key_exists($key, $this->_values)) { + return $this->_values[$key]; + } + + if ($key === 'schema') { + foreach (self::$TYPES as $schema => $types) { + if (array_search($this->_values['type'], $types)) { + return $schema; + } + } + } + } + + /** + * Return all the keys found on the page + * + * @return array + */ + public function keys() + { + return array_keys($this->_values); + } + + /** + * Helper method to check an attribute exists + * + * @param mixed $key + */ + public function __isset($key) + { + return array_key_exists($key, $this->_values); + } + + /** + * Will return true if the page has location data embedded + * + * @return boolean Check if the page has location data + */ + public function hasLocation() + { + if (array_key_exists('latitude', $this->_values) && array_key_exists('longitude', $this->_values)) { + return true; + } + + $address_keys = array('street_address', 'locality', 'region', 'postal_code', 'country_name'); + $valid_address = true; + foreach ($address_keys as $key) { + $valid_address = ($valid_address && array_key_exists($key, $this->_values)); + } + return $valid_address; + } + + /** + * Iterator code + */ + private $_position = 0; + + public function rewind() + { + reset($this->_values); + $this->_position = 0; + } + + public function current() + { + return current($this->_values); + } + + public function key() + { + return key($this->_values); + } + + public function next() + { + next($this->_values); + ++$this->_position; + } + + public function valid() + { + return $this->_position < sizeof($this->_values); + } } diff --git a/src/SimpleRequests.php b/src/SimpleRequests.php index b2d02a4..ddebcd7 100644 --- a/src/SimpleRequests.php +++ b/src/SimpleRequests.php @@ -27,223 +27,223 @@ */ class SimpleRequests { - protected $DEBUG = false; - protected $logger = null; - protected $logger_path = null; - protected $timeout = 60; - protected $header = array(); - - /** - * SimpleRequests constructor. - * - * @param $options - * @copyright: 713uk13m - * @author : 713uk13m - */ - public function __construct($options = []) - { - $monolog = array( - 'dateFormat' => "Y-m-d H:i:s u", - 'outputFormat' => "[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n", - 'monoBubble' => true, - 'monoFilePermission' => 0777 - ); - - if (isset($options['logger_path'])) { - $this->logger_path = $options['logger_path']; - } - - if (isset($options['debug_status'])) { - $this->DEBUG = $options['debug_status']; - } - - // create a log channel - $formatter = new LineFormatter($monolog['outputFormat'], $monolog['dateFormat']); - $stream = new StreamHandler( - $this->logger_path . 'Simple-Requests/Log-' . date('Y-m-d') . '.log', - Logger::INFO, - $monolog['monoBubble'], - $monolog['monoFilePermission'] - ); - $stream->setFormatter($formatter); - $this->logger = new Logger('SimpleRequests'); - $this->logger->pushHandler($stream); - } - - /** - * Function setTimeout - * - * @param $timeout - * - * @return $this - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 07/27/2021 31:11z - */ - public function setTimeout($timeout) - { - $this->timeout = $timeout; - return $this; - } - - /** - * Function setHeader - * - * @param array $header - * - * @return $this - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 07/27/2021 31:22 - */ - public function setHeader($header = array()) - { - $this->header = $header; - return $this; - } - - /** - * Function sendRequest - * - * @param string $url - * @param array $data - * @param string $method - * - * @return string|null - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 09/18/2021 54:32 - */ - public function sendRequest($url = '', $data = array(), $method = 'GET') - { - try { - $getMethod = mb_strtoupper($method); - if ($this->DEBUG === true) { - $this->logger->info('||=========== Logger Send Requests ===========||'); - $this->logger->info('Send ' . $getMethod . ' Request to URL: ' . $url, $data); - } - - $curl = new BasicCurl(); - $curl->setOpt(CURLOPT_RETURNTRANSFER, true); - $curl->setOpt(CURLOPT_SSL_VERIFYPEER, false); - $curl->setOpt(CURLOPT_ENCODING, "utf-8"); - $curl->setOpt(CURLOPT_MAXREDIRS, 10); - $curl->setOpt(CURLOPT_TIMEOUT, 300); - - if ('POST' === $getMethod) { - $curl->post($url, $data); - } else { - $curl->get($url, $data); - } - - - if ($curl->error) { - $response = "cURL Error: " . $curl->error_message; - } else { - $response = $curl->response; - } - - - $curl->close(); - - - if ($this->DEBUG === true) { - if (is_array($response) || is_object($response)) { - $this->logger->info('Response: ' . json_encode($response)); - } else { - $this->logger->info('Response: ' . $response); - } - - if (isset($curl->request_headers)) { - if (is_array($curl->request_headers)) { - $this->logger->info('Request Header: ', $curl->request_headers); - } else { - $this->logger->info('Request Header: ' . json_encode($curl->request_headers)); - } - } - - if (isset($curl->response_headers)) { - if (is_array($curl->response_headers)) { - $this->logger->info('Response Header: ', $curl->response_headers); - } else { - $this->logger->info('Response Header: ' . json_encode($curl->response_headers)); - } - } - } - - return $response; - } catch (Exception $e) { - log_message('error', __get_error_message__($e)); - log_message('error', __get_error_trace__($e)); - return null; - } - } - - /** - * Function xmlRequest - * - * @param string $url - * @param string $data - * @param int $timeout - * - * @return bool|string|null - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 07/27/2021 32:35 - */ - public function xmlRequest($url = '', $data = '', $timeout = 60) - { - if (empty($url) || empty($data)) { - return null; - } - - try { - if ($this->DEBUG === true) { - $this->logger->info('||=========== Logger xmlRequest ===========||'); - $this->logger->info('Send POST XML Request to URL: ' . $url . ' with DATA: ' . $data); - } - - $ch = curl_init(); - curl_setopt($ch, CURLOPT_URL, $url); - $head[] = "Content-type: text/xml;charset=utf-8"; - curl_setopt($ch, CURLOPT_HTTPHEADER, $head); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); - curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); - curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); - curl_setopt($ch, CURLOPT_POST, 1); - curl_setopt($ch, CURLOPT_POSTFIELDS, $data); - $response = curl_exec($ch); - curl_close($ch); - - if ($this->DEBUG === true) { - $this->logger->info('Response from Request: ' . $response); - } - - return $response; - } catch (Exception $e) { - log_message('error', __get_error_message__($e)); - log_message('error', __get_error_trace__($e)); - return null; - } - } - - /** - * Function xmlGetValue - * - * @param $xml - * @param $openTag - * @param $closeTag - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 07/08/2023 49:39 - */ - public function xmlGetValue($xml, $openTag, $closeTag) - { - $f = mb_strpos($xml, $openTag) + mb_strlen($openTag); - $l = mb_strpos($xml, $closeTag); - return ($f <= $l) ? mb_substr($xml, $f, $l - $f) : ""; - } + protected $DEBUG = false; + protected $logger = null; + protected $logger_path = null; + protected $timeout = 60; + protected $header = array(); + + /** + * SimpleRequests constructor. + * + * @param $options + * @copyright: 713uk13m + * @author : 713uk13m + */ + public function __construct($options = []) + { + $monolog = array( + 'dateFormat' => "Y-m-d H:i:s u", + 'outputFormat' => "[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n", + 'monoBubble' => true, + 'monoFilePermission' => 0777 + ); + + if (isset($options['logger_path'])) { + $this->logger_path = $options['logger_path']; + } + + if (isset($options['debug_status'])) { + $this->DEBUG = $options['debug_status']; + } + + // create a log channel + $formatter = new LineFormatter($monolog['outputFormat'], $monolog['dateFormat']); + $stream = new StreamHandler( + $this->logger_path . 'Simple-Requests/Log-' . date('Y-m-d') . '.log', + Logger::INFO, + $monolog['monoBubble'], + $monolog['monoFilePermission'] + ); + $stream->setFormatter($formatter); + $this->logger = new Logger('SimpleRequests'); + $this->logger->pushHandler($stream); + } + + /** + * Function setTimeout + * + * @param $timeout + * + * @return $this + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 07/27/2021 31:11z + */ + public function setTimeout($timeout) + { + $this->timeout = $timeout; + return $this; + } + + /** + * Function setHeader + * + * @param array $header + * + * @return $this + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 07/27/2021 31:22 + */ + public function setHeader($header = array()) + { + $this->header = $header; + return $this; + } + + /** + * Function sendRequest + * + * @param string $url + * @param array $data + * @param string $method + * + * @return string|null + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 09/18/2021 54:32 + */ + public function sendRequest($url = '', $data = array(), $method = 'GET') + { + try { + $getMethod = mb_strtoupper($method); + if ($this->DEBUG === true) { + $this->logger->info('||=========== Logger Send Requests ===========||'); + $this->logger->info('Send ' . $getMethod . ' Request to URL: ' . $url, $data); + } + + $curl = new BasicCurl(); + $curl->setOpt(CURLOPT_RETURNTRANSFER, true); + $curl->setOpt(CURLOPT_SSL_VERIFYPEER, false); + $curl->setOpt(CURLOPT_ENCODING, "utf-8"); + $curl->setOpt(CURLOPT_MAXREDIRS, 10); + $curl->setOpt(CURLOPT_TIMEOUT, 300); + + if ('POST' === $getMethod) { + $curl->post($url, $data); + } else { + $curl->get($url, $data); + } + + + if ($curl->error) { + $response = "cURL Error: " . $curl->error_message; + } else { + $response = $curl->response; + } + + + $curl->close(); + + + if ($this->DEBUG === true) { + if (is_array($response) || is_object($response)) { + $this->logger->info('Response: ' . json_encode($response)); + } else { + $this->logger->info('Response: ' . $response); + } + + if (isset($curl->request_headers)) { + if (is_array($curl->request_headers)) { + $this->logger->info('Request Header: ', $curl->request_headers); + } else { + $this->logger->info('Request Header: ' . json_encode($curl->request_headers)); + } + } + + if (isset($curl->response_headers)) { + if (is_array($curl->response_headers)) { + $this->logger->info('Response Header: ', $curl->response_headers); + } else { + $this->logger->info('Response Header: ' . json_encode($curl->response_headers)); + } + } + } + + return $response; + } catch (Exception $e) { + log_message('error', __get_error_message__($e)); + log_message('error', __get_error_trace__($e)); + return null; + } + } + + /** + * Function xmlRequest + * + * @param string $url + * @param string $data + * @param int $timeout + * + * @return bool|string|null + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 07/27/2021 32:35 + */ + public function xmlRequest($url = '', $data = '', $timeout = 60) + { + if (empty($url) || empty($data)) { + return null; + } + + try { + if ($this->DEBUG === true) { + $this->logger->info('||=========== Logger xmlRequest ===========||'); + $this->logger->info('Send POST XML Request to URL: ' . $url . ' with DATA: ' . $data); + } + + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $url); + $head[] = "Content-type: text/xml;charset=utf-8"; + curl_setopt($ch, CURLOPT_HTTPHEADER, $head); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); + curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); + curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); + curl_setopt($ch, CURLOPT_POST, 1); + curl_setopt($ch, CURLOPT_POSTFIELDS, $data); + $response = curl_exec($ch); + curl_close($ch); + + if ($this->DEBUG === true) { + $this->logger->info('Response from Request: ' . $response); + } + + return $response; + } catch (Exception $e) { + log_message('error', __get_error_message__($e)); + log_message('error', __get_error_trace__($e)); + return null; + } + } + + /** + * Function xmlGetValue + * + * @param $xml + * @param $openTag + * @param $closeTag + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 07/08/2023 49:39 + */ + public function xmlGetValue($xml, $openTag, $closeTag) + { + $f = mb_strpos($xml, $openTag) + mb_strlen($openTag); + $l = mb_strpos($xml, $closeTag); + return ($f <= $l) ? mb_substr($xml, $f, $l - $f) : ""; + } } diff --git a/src/SimpleRestful.php b/src/SimpleRestful.php index aab679d..fc9c53b 100644 --- a/src/SimpleRestful.php +++ b/src/SimpleRestful.php @@ -19,68 +19,68 @@ */ class SimpleRestful extends BaseHelper { - /** - * Function execute - * - * @param string $url - * @param string $type - * @param string $data - * @param mixed $header - * - * @return array|int - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 28/02/2022 25:41 - */ - public static function execute($url, $type, $data = "", $header = null) - { - $curl = curl_init(); + /** + * Function execute + * + * @param string $url + * @param string $type + * @param string $data + * @param mixed $header + * + * @return array|int + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 28/02/2022 25:41 + */ + public static function execute($url, $type, $data = "", $header = null) + { + $curl = curl_init(); - if (empty($header)) { - $header = array("Content-Type: application/json"); - } + if (empty($header)) { + $header = array("Content-Type: application/json"); + } - $url = rtrim($url, "/"); - $parseUrl = parse_url($url); + $url = rtrim($url, "/"); + $parseUrl = parse_url($url); - $options = array( - CURLOPT_URL => $url, - CURLOPT_RETURNTRANSFER => true, - CURLOPT_ENCODING => "", - CURLOPT_MAXREDIRS => 10, - CURLOPT_TIMEOUT => 30, - CURLOPT_CUSTOMREQUEST => $type, - CURLOPT_POSTFIELDS => $data, - CURLOPT_HTTPHEADER => $header, - CURLOPT_SSL_VERIFYHOST => 0, - CURLOPT_SSL_VERIFYPEER => 0, - ); + $options = array( + CURLOPT_URL => $url, + CURLOPT_RETURNTRANSFER => true, + CURLOPT_ENCODING => "", + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 30, + CURLOPT_CUSTOMREQUEST => $type, + CURLOPT_POSTFIELDS => $data, + CURLOPT_HTTPHEADER => $header, + CURLOPT_SSL_VERIFYHOST => 0, + CURLOPT_SSL_VERIFYPEER => 0, + ); - if (isset($parseUrl['scheme']) && $parseUrl['scheme'] === 'https') { - $options[CURLOPT_SSLVERSION] = CURL_SSLVERSION_TLSv1_2; - } + if (isset($parseUrl['scheme']) && $parseUrl['scheme'] === 'https') { + $options[CURLOPT_SSLVERSION] = CURL_SSLVERSION_TLSv1_2; + } - if (isset($parseUrl['scheme']) && $parseUrl['scheme'] === 'http') { - $options[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_1; - } + if (isset($parseUrl['scheme']) && $parseUrl['scheme'] === 'http') { + $options[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_1; + } - curl_setopt_array($curl, $options); + curl_setopt_array($curl, $options); - $response = json_decode(curl_exec($curl)); + $response = json_decode(curl_exec($curl)); - unset($response->response_time); + unset($response->response_time); - $err = curl_error($curl); - $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); + $err = curl_error($curl); + $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); - curl_close($curl); + curl_close($curl); - if ($err) { - echo "cURL Error #:" . $err; + if ($err) { + echo "cURL Error #:" . $err; - return -1; - } + return -1; + } - return array('code' => $httpCode, 'response' => $response); - } + return array('code' => $httpCode, 'response' => $response); + } } diff --git a/src/SimpleVerifiedKey.php b/src/SimpleVerifiedKey.php index c1c8b0a..f702ed8 100644 --- a/src/SimpleVerifiedKey.php +++ b/src/SimpleVerifiedKey.php @@ -19,44 +19,44 @@ */ class SimpleVerifiedKey extends BaseHelper { - public $remotePublicKey = <<remotePrivateKey; - } + public function getRemotePrivateKey() + { + return $this->remotePrivateKey; + } - public function getRemotePublicKey() - { - return $this->remotePublicKey; - } + public function getRemotePublicKey() + { + return $this->remotePublicKey; + } - public function getClientPrivateKey() - { - return $this->clientPrivateKey; - } + public function getClientPrivateKey() + { + return $this->clientPrivateKey; + } - public function getClientPublicKey() - { - return $this->clientPublicKey; - } + public function getClientPublicKey() + { + return $this->clientPublicKey; + } } diff --git a/src/SimpleVisitor.php b/src/SimpleVisitor.php index 0df3a8d..0b53cb4 100644 --- a/src/SimpleVisitor.php +++ b/src/SimpleVisitor.php @@ -22,126 +22,126 @@ */ class SimpleVisitor extends BaseHelper { - const CCU_SESSION_ID = 'session_id_visitor_onload_ccu_'; - const CCU_SESSION_VALUE = 'YES'; - - protected $filename; - protected $sessClass; - protected $sessId; - protected $outputClass; - - public function setFilename($filename) - { - $this->filename = $filename; - - return $this; - } - - public function setSessClass($sessClass) - { - $this->sessClass = $sessClass; - - return $this; - } - - public function setSessId($sessId) - { - $this->sessId = $sessId; - - return $this; - } - - - public function setOutputClass($outputClass) - { - $this->outputClass = $outputClass; - - return $this; - } - - public function totalVisitor() - { - $CountFile = $this->filename; - if ( ! file_exists($CountFile)) { - return 0; - } - $CF = fopen($CountFile, 'rb'); - $Views = fread($CF, filesize($CountFile)); - fclose($CF); - $Views++; - $CF = fopen($CountFile, 'wb'); - fwrite($CF, $Views); - fclose($CF); - - return $Views; - } - - public function ccuOnload() - { - $CountFile = $this->filename; - if ( ! file_exists($CountFile)) { - return 0; - } - $myfile = fopen($CountFile, "r") or die("Unable to open file!"); - $before = fread($myfile, filesize($CountFile)); - fclose($myfile); - - if (empty($this->sessId)) { - $this->sessId = self::CCU_SESSION_ID; - } - - if ($this->sessClass->userdata($this->sessId . date('Y_m_d')) === self::CCU_SESSION_VALUE) { - $this->outputClass->set_content_type('application/json')->set_output($before)->_display(); - exit(); - } - - $this->sessClass->set_userdata($this->sessId . date('Y_m_d'), self::CCU_SESSION_VALUE); - $myfile = fopen($CountFile, "w") or die("Unable to open file!"); - $after = $before + 1; - fwrite($myfile, $after); - fclose($myfile); - - $this->outputClass->set_content_type('application/json')->set_output($after)->_display(); - exit(); - } - - public function ccuOnclose() - { - if (empty($this->sessId)) { - $this->sessId = self::CCU_SESSION_ID; - } - - $this->sessClass->unset_userdata($this->sessId . date('Y_m_d')); - $CountFile = $this->filename; - if ( ! file_exists($CountFile)) { - return 0; - } - $myfile = fopen($CountFile, "r") or die("Unable to open file!"); - $before = fread($myfile, filesize($CountFile)); - fclose($myfile); - $myfile = fopen($CountFile, "w") or die("Unable to open file!"); - $after = $before - 1; - fwrite($myfile, $after); - fclose($myfile); - $this->outputClass->set_content_type('application/json')->set_output($after)->_display(); - exit(); - } - - public function ccuTruncate() - { - if ( ! is_cli()) { - show_404(); - exit(); - } - $CountFile = $this->filename; - if ( ! file_exists($CountFile)) { - return 0; - } - $myfile = fopen($CountFile, "w") or die("Unable to open file!"); - $truncateNumber = 5; - fwrite($myfile, $truncateNumber); - fclose($myfile); - self::writeLn("Update CCU count: " . $truncateNumber); - exit(); - } + const CCU_SESSION_ID = 'session_id_visitor_onload_ccu_'; + const CCU_SESSION_VALUE = 'YES'; + + protected $filename; + protected $sessClass; + protected $sessId; + protected $outputClass; + + public function setFilename($filename) + { + $this->filename = $filename; + + return $this; + } + + public function setSessClass($sessClass) + { + $this->sessClass = $sessClass; + + return $this; + } + + public function setSessId($sessId) + { + $this->sessId = $sessId; + + return $this; + } + + + public function setOutputClass($outputClass) + { + $this->outputClass = $outputClass; + + return $this; + } + + public function totalVisitor() + { + $CountFile = $this->filename; + if (!file_exists($CountFile)) { + return 0; + } + $CF = fopen($CountFile, 'rb'); + $Views = fread($CF, filesize($CountFile)); + fclose($CF); + $Views++; + $CF = fopen($CountFile, 'wb'); + fwrite($CF, $Views); + fclose($CF); + + return $Views; + } + + public function ccuOnload() + { + $CountFile = $this->filename; + if (!file_exists($CountFile)) { + return 0; + } + $myfile = fopen($CountFile, "r") or die("Unable to open file!"); + $before = fread($myfile, filesize($CountFile)); + fclose($myfile); + + if (empty($this->sessId)) { + $this->sessId = self::CCU_SESSION_ID; + } + + if ($this->sessClass->userdata($this->sessId . date('Y_m_d')) === self::CCU_SESSION_VALUE) { + $this->outputClass->set_content_type('application/json')->set_output($before)->_display(); + exit(); + } + + $this->sessClass->set_userdata($this->sessId . date('Y_m_d'), self::CCU_SESSION_VALUE); + $myfile = fopen($CountFile, "w") or die("Unable to open file!"); + $after = $before + 1; + fwrite($myfile, $after); + fclose($myfile); + + $this->outputClass->set_content_type('application/json')->set_output($after)->_display(); + exit(); + } + + public function ccuOnclose() + { + if (empty($this->sessId)) { + $this->sessId = self::CCU_SESSION_ID; + } + + $this->sessClass->unset_userdata($this->sessId . date('Y_m_d')); + $CountFile = $this->filename; + if (!file_exists($CountFile)) { + return 0; + } + $myfile = fopen($CountFile, "r") or die("Unable to open file!"); + $before = fread($myfile, filesize($CountFile)); + fclose($myfile); + $myfile = fopen($CountFile, "w") or die("Unable to open file!"); + $after = $before - 1; + fwrite($myfile, $after); + fclose($myfile); + $this->outputClass->set_content_type('application/json')->set_output($after)->_display(); + exit(); + } + + public function ccuTruncate() + { + if (!is_cli()) { + show_404(); + exit(); + } + $CountFile = $this->filename; + if (!file_exists($CountFile)) { + return 0; + } + $myfile = fopen($CountFile, "w") or die("Unable to open file!"); + $truncateNumber = 5; + fwrite($myfile, $truncateNumber); + fclose($myfile); + self::writeLn("Update CCU count: " . $truncateNumber); + exit(); + } } diff --git a/src/Valid.php b/src/Valid.php index 74b0316..7179733 100644 --- a/src/Valid.php +++ b/src/Valid.php @@ -14,165 +14,165 @@ class Valid extends BaseHelper { - /** - * Checks if a field is not empty. - * - * @return boolean - */ - public static function not_empty($value) - { - if (is_object($value) and $value instanceof ArrayObject) { - // Get the array from the ArrayObject - $value = $value->getArrayCopy(); - } - - // Value cannot be NULL, FALSE, '', or an empty array - return ! in_array($value, array(null, false, '', array()), true); - } - - /** - * Checks a field against a regular expression. - * - * @param string $value value - * @param string $expression regular expression to match (including delimiters) - * - * @return boolean - */ - public static function regex($value, $expression) - { - return (bool)preg_match($expression, (string)$value); - } - - /** - * Checks that a field is long enough. - * - * @param string $value value - * @param integer $length minimum length required - * - * @return boolean - */ - public static function min_length($value, $length) - { - return mb_strlen($value) >= $length; - } - - /** - * Checks that a field is short enough. - * - * @param string $value value - * @param integer $length maximum length required - * - * @return boolean - */ - public static function max_length($value, $length) - { - return mb_strlen($value) <= $length; - } - - /** - * Checks that a field is exactly the right length. - * - * @param string $value value - * @param integer|array $length exact length required, or array of valid lengths - * - * @return boolean - */ - public static function exact_length($value, $length) - { - if (is_array($length)) { - if (in_array(mb_strlen($value), $length)) { - return true; - } - - return false; - } - - return mb_strlen($value) === $length; - } - - /** - * Checks that a field is exactly the value required. - * - * @param string $value value - * @param string $required required value - * - * @return boolean - */ - public static function equals($value, $required) - { - return ($value === $required); - } - - /** - * Check an email address for correct format. - * - * @link http://www.iamcal.com/publish/articles/php/parsing_email/ - * @link http://www.w3.org/Protocols/rfc822/ - * - * @param string $email email address - * @param boolean $strict strict RFC compatibility - * - * @return boolean - */ - public static function email($email, $strict = false) - { - if (mb_strlen($email) > 254) { - return false; - } - - if ($strict === true) { - $qtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]'; - $dtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]'; - $atom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+'; - $pair = '\\x5c[\\x00-\\x7f]'; - - $domain_literal = "\\x5b($dtext|$pair)*\\x5d"; - $quoted_string = "\\x22($qtext|$pair)*\\x22"; - $sub_domain = "($atom|$domain_literal)"; - $word = "($atom|$quoted_string)"; - $domain = "$sub_domain(\\x2e$sub_domain)*"; - $local_part = "$word(\\x2e$word)*"; - - $expression = "/^$local_part\\x40$domain$/D"; - } else { - $expression = '/^[-_a-z0-9\'+*$^&%=~!?{}]++(?:\.[-_a-z0-9\'+*$^&%=~!?{}]+)*+@(?:(?![-.])[-a-z0-9.]+(?getArrayCopy(); + } + + // Value cannot be NULL, FALSE, '', or an empty array + return !in_array($value, array(null, false, '', array()), true); + } + + /** + * Checks a field against a regular expression. + * + * @param string $value value + * @param string $expression regular expression to match (including delimiters) + * + * @return boolean + */ + public static function regex($value, $expression) + { + return (bool)preg_match($expression, (string)$value); + } + + /** + * Checks that a field is long enough. + * + * @param string $value value + * @param integer $length minimum length required + * + * @return boolean + */ + public static function min_length($value, $length) + { + return mb_strlen($value) >= $length; + } + + /** + * Checks that a field is short enough. + * + * @param string $value value + * @param integer $length maximum length required + * + * @return boolean + */ + public static function max_length($value, $length) + { + return mb_strlen($value) <= $length; + } + + /** + * Checks that a field is exactly the right length. + * + * @param string $value value + * @param integer|array $length exact length required, or array of valid lengths + * + * @return boolean + */ + public static function exact_length($value, $length) + { + if (is_array($length)) { + if (in_array(mb_strlen($value), $length)) { + return true; + } + + return false; + } + + return mb_strlen($value) === $length; + } + + /** + * Checks that a field is exactly the value required. + * + * @param string $value value + * @param string $required required value + * + * @return boolean + */ + public static function equals($value, $required) + { + return ($value === $required); + } + + /** + * Check an email address for correct format. + * + * @link http://www.iamcal.com/publish/articles/php/parsing_email/ + * @link http://www.w3.org/Protocols/rfc822/ + * + * @param string $email email address + * @param boolean $strict strict RFC compatibility + * + * @return boolean + */ + public static function email($email, $strict = false) + { + if (mb_strlen($email) > 254) { + return false; + } + + if ($strict === true) { + $qtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]'; + $dtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]'; + $atom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+'; + $pair = '\\x5c[\\x00-\\x7f]'; + + $domain_literal = "\\x5b($dtext|$pair)*\\x5d"; + $quoted_string = "\\x22($qtext|$pair)*\\x22"; + $sub_domain = "($atom|$domain_literal)"; + $word = "($atom|$quoted_string)"; + $domain = "$sub_domain(\\x2e$sub_domain)*"; + $local_part = "$word(\\x2e$word)*"; + + $expression = "/^$local_part\\x40$domain$/D"; + } else { + $expression = '/^[-_a-z0-9\'+*$^&%=~!?{}]++(?:\.[-_a-z0-9\'+*$^&%=~!?{}]+)*+@(?:(?![-.])[-a-z0-9.]+(? 253) { - return false; - } - - // An extra check for the top level domain - // It must start with a letter - $tld = ltrim(mb_substr($matches[1], (int)strrpos($matches[1], '.')), '.'); - - return ctype_alpha($tld[0]); - } - - /** - * Validate an IP. - * - * @param string $ip IP address - * @param boolean $allow_private allow private IP networks - * - * @return boolean - */ - public static function ip($ip, $allow_private = true) - { - // Do not allow reserved addresses - $flags = FILTER_FLAG_NO_RES_RANGE; - - if ($allow_private === false) { - // Do not allow private or reserved addresses - $flags = $flags | FILTER_FLAG_NO_PRIV_RANGE; - } - - return (bool)filter_var($ip, FILTER_VALIDATE_IP, $flags); - } - - /** - * Validates a credit card number, with a Luhn check if possible. - * - * @param integer $number credit card number - * @param string|array $type card type, or an array of card types - * - * @return boolean - */ - public static function credit_card($number, $type = null) - { - // Remove all non-digit characters from the number - if (($number = preg_replace('/\D+/', '', $number)) === '') { - return false; - } - - if ($type === null) { - // Use the default type - $type = 'default'; - } elseif (is_array($type)) { - foreach ($type as $t) { - // Test each type for validity - if (self::credit_card($number, $t)) { - return true; - } - } - - return false; - } - - /** - * Credit card validation configuration. - * - * Options for each credit card: - * length - All the allowed card number lengths, in a comma separated string - * prefix - The digits the card needs to start with, in regex format - * luhn - Enable or disable card number validation by the Luhn algorithm - */ - $cards = array( - - 'default' => array( - 'length' => '13,14,15,16,17,18,19', - 'prefix' => '', - 'luhn' => true, - ), - - 'american express' => array( - 'length' => '15', - 'prefix' => '3[47]', - 'luhn' => true, - ), - - 'diners club' => array( - 'length' => '14,16', - 'prefix' => '36|55|30[0-5]', - 'luhn' => true, - ), - - 'discover' => array( - 'length' => '16', - 'prefix' => '6(?:5|011)', - 'luhn' => true, - ), - - 'jcb' => array( - 'length' => '15,16', - 'prefix' => '3|1800|2131', - 'luhn' => true, - ), - - 'maestro' => array( - 'length' => '16,18', - 'prefix' => '50(?:20|38)|6(?:304|759)', - 'luhn' => true, - ), - - 'mastercard' => array( - 'length' => '16', - 'prefix' => '5[1-5]', - 'luhn' => true, - ), - - 'visa' => array( - 'length' => '13,16', - 'prefix' => '4', - 'luhn' => true, - ), - - ); - - // Check card type - $type = mb_strtolower($type); - - if ( ! isset($cards[$type])) { - return false; - } - - // Check card number length - $length = mb_strlen($number); - - // Validate the card length by the card type - if ( ! in_array($length, preg_split('/\D+/', $cards[$type]['length']))) { - return false; - } - - // Check card number prefix - if ( ! preg_match('/^' . $cards[$type]['prefix'] . '/', $number)) { - return false; - } - - // No Luhn check required - if ($cards[$type]['luhn'] === false) { - return true; - } - - return self::luhn($number); - } - - /** - * Validate a number against the [Luhn](http://en.wikipedia.org/wiki/Luhn_algorithm) - * (mod10) formula. - * - * @param string $number number to check - * - * @return boolean - */ - public static function luhn($number) - { - // Force the value to be a string as this method uses string functions. - // Converting to an integer may pass PHP_INT_MAX and result in an error! - $number = (string)$number; - - if ( ! ctype_digit($number)) { - // Luhn can only be used on numbers! - return false; - } - - // Check number length - $length = mb_strlen($number); - - // Checksum of the card number - $checksum = 0; - - for ($i = $length - 1; $i >= 0; $i -= 2) { - // Add up every 2nd digit, starting from the right - $checksum += mb_substr($number, $i, 1); - } - - for ($i = $length - 2; $i >= 0; $i -= 2) { - // Add up every 2nd digit doubled, starting from the right - $double = mb_substr($number, $i, 1) * 2; - - // Subtract 9 from the double where value is greater than 10 - $checksum += ($double >= 10) ? ($double - 9) : $double; - } - - // If the checksum is a multiple of 10, the number is valid - return ($checksum % 10 === 0); - } - - /** - * Checks if a phone number is valid. - * - * @param string $number phone number to check - * @param array $lengths - * - * @return boolean - */ - public static function phone($number, $lengths = null) - { - if ( ! is_array($lengths)) { - $lengths = array(7, 10, 11); - } - - // Remove all non-digit characters from the number - $number = preg_replace('/\D+/', '', $number); - - // Check if the number is within range - return in_array(mb_strlen($number), $lengths); - } - - /** - * Tests if a string is a valid date string. - * - * @param string $str date to check - * - * @return boolean - */ - public static function date($str) - { - return (strtotime($str) !== false); - } - - /** - * Checks whether a string consists of alphabetical characters only. - * - * @param string $str input string - * @param boolean $utf8 trigger UTF-8 compatibility - * - * @return boolean - */ - public static function alpha($str, $utf8 = false) - { - $str = (string)$str; - - if ($utf8 === true) { - return (bool)preg_match('/^\pL++$/uD', $str); - } - - return ctype_alpha($str); - } - - /** - * Checks whether a string consists of alphabetical characters and numbers only. - * - * @param string $str input string - * @param boolean $utf8 trigger UTF-8 compatibility - * - * @return boolean - */ - public static function alpha_numeric($str, $utf8 = false) - { - if ($utf8 === true) { - return (bool)preg_match('/^[\pL\pN]++$/uD', $str); - } else { - return ctype_alnum($str); - } - } - - /** - * Checks whether a string consists of alphabetical characters, numbers, underscores and dashes only. - * - * @param string $str input string - * @param boolean $utf8 trigger UTF-8 compatibility - * - * @return boolean - */ - public static function alpha_dash($str, $utf8 = false) - { - if ($utf8 === true) { - $regex = '/^[-\pL\pN_]++$/uD'; - } else { - $regex = '/^[-a-z0-9_]++$/iD'; - } - - return (bool)preg_match($regex, $str); - } - - /** - * Checks whether a string consists of digits only (no dots or dashes). - * - * @param string $str input string - * @param boolean $utf8 trigger UTF-8 compatibility - * - * @return boolean - */ - public static function digit($str, $utf8 = false) - { - if ($utf8 === true) { - return (bool)preg_match('/^\pN++$/uD', $str); - } - - return (is_int($str) and $str >= 0) or ctype_digit($str); - } - - /** - * Checks whether a string is a valid number (negative and decimal numbers allowed). - * - * Uses {@link http://www.php.net/manual/en/function.localeconv.php locale conversion} - * to allow decimal point to be locale specific. - * - * @param string $str input string - * - * @return boolean - */ - public static function numeric($str) - { - // Get the decimal point for the current locale - list($decimal) = array_values(localeconv()); - - // A lookahead is used to make sure the string contains at least one digit (before or after the decimal point) - return (bool)preg_match('/^-?+(?=.*[0-9])[0-9]*+' . preg_quote($decimal) . '?+[0-9]*+$/D', (string)$str); - } - - /** - * Tests if a number is within a range. - * - * @param string $number number to check - * @param integer $min minimum value - * @param integer $max maximum value - * @param integer $step increment size - * - * @return boolean - */ - public static function range($number, $min, $max, $step = null) - { - if ($number < $min or $number > $max) { - // Number is outside of range - return false; - } - - if ( ! $step) { - // Default to steps of 1 - $step = 1; - } - - // Check step requirements - return (($number - $min) % $step === 0); - } - - /** - * Checks if a string is a proper decimal format. Optionally, a specific - * number of digits can be checked too. - * - * @param string $str number to check - * @param integer $places number of decimal places - * @param integer $digits number of digits - * - * @return boolean - */ - public static function decimal($str, $places = 2, $digits = null) - { - if ($digits > 0) { - // Specific number of digits - $digits = '{' . ((int)$digits) . '}'; - } else { - // Any number of digits - $digits = '+'; - } - - // Get the decimal point for the current locale - list($decimal) = array_values(localeconv()); - - return (bool)preg_match( - '/^[+-]?[0-9]' . $digits . preg_quote($decimal) . '[0-9]{' . ((int)$places) . '}$/D', - $str - ); - } - - /** - * Checks if a string is a proper hexadecimal HTML color value. The validation - * is quite flexible as it does not require an initial "#" and also allows for - * the short notation using only three instead of six hexadecimal characters. - * - * @param string $str input string - * - * @return boolean - */ - public static function color($str) - { - return (bool)preg_match('/^#?+[0-9a-f]{3}(?:[0-9a-f]{3})?$/iD', $str); - } - - /** - * Checks if a field matches the value of another field. - * - * @param array $array array of values - * @param string $field field name - * @param string $match field name to match - * - * @return boolean - */ - public static function matches($array, $field, $match) - { - return ($array[$field] === $array[$match]); - } + $url, + $matches + )) { + return false; + } + + // We matched an IP address + if (!isset($matches[1])) { + return true; + } + + // Check maximum length of the whole hostname + // http://en.wikipedia.org/wiki/Domain_name#cite_note-0 + if (mb_strlen($matches[1]) > 253) { + return false; + } + + // An extra check for the top level domain + // It must start with a letter + $tld = ltrim(mb_substr($matches[1], (int)strrpos($matches[1], '.')), '.'); + + return ctype_alpha($tld[0]); + } + + /** + * Validate an IP. + * + * @param string $ip IP address + * @param boolean $allow_private allow private IP networks + * + * @return boolean + */ + public static function ip($ip, $allow_private = true) + { + // Do not allow reserved addresses + $flags = FILTER_FLAG_NO_RES_RANGE; + + if ($allow_private === false) { + // Do not allow private or reserved addresses + $flags = $flags | FILTER_FLAG_NO_PRIV_RANGE; + } + + return (bool)filter_var($ip, FILTER_VALIDATE_IP, $flags); + } + + /** + * Validates a credit card number, with a Luhn check if possible. + * + * @param integer $number credit card number + * @param string|array $type card type, or an array of card types + * + * @return boolean + */ + public static function credit_card($number, $type = null) + { + // Remove all non-digit characters from the number + if (($number = preg_replace('/\D+/', '', $number)) === '') { + return false; + } + + if ($type === null) { + // Use the default type + $type = 'default'; + } elseif (is_array($type)) { + foreach ($type as $t) { + // Test each type for validity + if (self::credit_card($number, $t)) { + return true; + } + } + + return false; + } + + /** + * Credit card validation configuration. + * + * Options for each credit card: + * length - All the allowed card number lengths, in a comma separated string + * prefix - The digits the card needs to start with, in regex format + * luhn - Enable or disable card number validation by the Luhn algorithm + */ + $cards = array( + + 'default' => array( + 'length' => '13,14,15,16,17,18,19', + 'prefix' => '', + 'luhn' => true, + ), + + 'american express' => array( + 'length' => '15', + 'prefix' => '3[47]', + 'luhn' => true, + ), + + 'diners club' => array( + 'length' => '14,16', + 'prefix' => '36|55|30[0-5]', + 'luhn' => true, + ), + + 'discover' => array( + 'length' => '16', + 'prefix' => '6(?:5|011)', + 'luhn' => true, + ), + + 'jcb' => array( + 'length' => '15,16', + 'prefix' => '3|1800|2131', + 'luhn' => true, + ), + + 'maestro' => array( + 'length' => '16,18', + 'prefix' => '50(?:20|38)|6(?:304|759)', + 'luhn' => true, + ), + + 'mastercard' => array( + 'length' => '16', + 'prefix' => '5[1-5]', + 'luhn' => true, + ), + + 'visa' => array( + 'length' => '13,16', + 'prefix' => '4', + 'luhn' => true, + ), + + ); + + // Check card type + $type = mb_strtolower($type); + + if (!isset($cards[$type])) { + return false; + } + + // Check card number length + $length = mb_strlen($number); + + // Validate the card length by the card type + if (!in_array($length, preg_split('/\D+/', $cards[$type]['length']))) { + return false; + } + + // Check card number prefix + if (!preg_match('/^' . $cards[$type]['prefix'] . '/', $number)) { + return false; + } + + // No Luhn check required + if ($cards[$type]['luhn'] === false) { + return true; + } + + return self::luhn($number); + } + + /** + * Validate a number against the [Luhn](http://en.wikipedia.org/wiki/Luhn_algorithm) + * (mod10) formula. + * + * @param string $number number to check + * + * @return boolean + */ + public static function luhn($number) + { + // Force the value to be a string as this method uses string functions. + // Converting to an integer may pass PHP_INT_MAX and result in an error! + $number = (string)$number; + + if (!ctype_digit($number)) { + // Luhn can only be used on numbers! + return false; + } + + // Check number length + $length = mb_strlen($number); + + // Checksum of the card number + $checksum = 0; + + for ($i = $length - 1; $i >= 0; $i -= 2) { + // Add up every 2nd digit, starting from the right + $checksum += mb_substr($number, $i, 1); + } + + for ($i = $length - 2; $i >= 0; $i -= 2) { + // Add up every 2nd digit doubled, starting from the right + $double = mb_substr($number, $i, 1) * 2; + + // Subtract 9 from the double where value is greater than 10 + $checksum += ($double >= 10) ? ($double - 9) : $double; + } + + // If the checksum is a multiple of 10, the number is valid + return ($checksum % 10 === 0); + } + + /** + * Checks if a phone number is valid. + * + * @param string $number phone number to check + * @param array $lengths + * + * @return boolean + */ + public static function phone($number, $lengths = null) + { + if (!is_array($lengths)) { + $lengths = array(7, 10, 11); + } + + // Remove all non-digit characters from the number + $number = preg_replace('/\D+/', '', $number); + + // Check if the number is within range + return in_array(mb_strlen($number), $lengths); + } + + /** + * Tests if a string is a valid date string. + * + * @param string $str date to check + * + * @return boolean + */ + public static function date($str) + { + return (strtotime($str) !== false); + } + + /** + * Checks whether a string consists of alphabetical characters only. + * + * @param string $str input string + * @param boolean $utf8 trigger UTF-8 compatibility + * + * @return boolean + */ + public static function alpha($str, $utf8 = false) + { + $str = (string)$str; + + if ($utf8 === true) { + return (bool)preg_match('/^\pL++$/uD', $str); + } + + return ctype_alpha($str); + } + + /** + * Checks whether a string consists of alphabetical characters and numbers only. + * + * @param string $str input string + * @param boolean $utf8 trigger UTF-8 compatibility + * + * @return boolean + */ + public static function alpha_numeric($str, $utf8 = false) + { + if ($utf8 === true) { + return (bool)preg_match('/^[\pL\pN]++$/uD', $str); + } else { + return ctype_alnum($str); + } + } + + /** + * Checks whether a string consists of alphabetical characters, numbers, underscores and dashes only. + * + * @param string $str input string + * @param boolean $utf8 trigger UTF-8 compatibility + * + * @return boolean + */ + public static function alpha_dash($str, $utf8 = false) + { + if ($utf8 === true) { + $regex = '/^[-\pL\pN_]++$/uD'; + } else { + $regex = '/^[-a-z0-9_]++$/iD'; + } + + return (bool)preg_match($regex, $str); + } + + /** + * Checks whether a string consists of digits only (no dots or dashes). + * + * @param string $str input string + * @param boolean $utf8 trigger UTF-8 compatibility + * + * @return boolean + */ + public static function digit($str, $utf8 = false) + { + if ($utf8 === true) { + return (bool)preg_match('/^\pN++$/uD', $str); + } + + return (is_int($str) and $str >= 0) or ctype_digit($str); + } + + /** + * Checks whether a string is a valid number (negative and decimal numbers allowed). + * + * Uses {@link http://www.php.net/manual/en/function.localeconv.php locale conversion} + * to allow decimal point to be locale specific. + * + * @param string $str input string + * + * @return boolean + */ + public static function numeric($str) + { + // Get the decimal point for the current locale + list($decimal) = array_values(localeconv()); + + // A lookahead is used to make sure the string contains at least one digit (before or after the decimal point) + return (bool)preg_match('/^-?+(?=.*[0-9])[0-9]*+' . preg_quote($decimal) . '?+[0-9]*+$/D', (string)$str); + } + + /** + * Tests if a number is within a range. + * + * @param string $number number to check + * @param integer $min minimum value + * @param integer $max maximum value + * @param integer $step increment size + * + * @return boolean + */ + public static function range($number, $min, $max, $step = null) + { + if ($number < $min or $number > $max) { + // Number is outside of range + return false; + } + + if (!$step) { + // Default to steps of 1 + $step = 1; + } + + // Check step requirements + return (($number - $min) % $step === 0); + } + + /** + * Checks if a string is a proper decimal format. Optionally, a specific + * number of digits can be checked too. + * + * @param string $str number to check + * @param integer $places number of decimal places + * @param integer $digits number of digits + * + * @return boolean + */ + public static function decimal($str, $places = 2, $digits = null) + { + if ($digits > 0) { + // Specific number of digits + $digits = '{' . ((int)$digits) . '}'; + } else { + // Any number of digits + $digits = '+'; + } + + // Get the decimal point for the current locale + list($decimal) = array_values(localeconv()); + + return (bool)preg_match( + '/^[+-]?[0-9]' . $digits . preg_quote($decimal) . '[0-9]{' . ((int)$places) . '}$/D', + $str + ); + } + + /** + * Checks if a string is a proper hexadecimal HTML color value. The validation + * is quite flexible as it does not require an initial "#" and also allows for + * the short notation using only three instead of six hexadecimal characters. + * + * @param string $str input string + * + * @return boolean + */ + public static function color($str) + { + return (bool)preg_match('/^#?+[0-9a-f]{3}(?:[0-9a-f]{3})?$/iD', $str); + } + + /** + * Checks if a field matches the value of another field. + * + * @param array $array array of values + * @param string $field field name + * @param string $match field name to match + * + * @return boolean + */ + public static function matches($array, $field, $match) + { + return ($array[$field] === $array[$match]); + } } diff --git a/src/Validator.php b/src/Validator.php index 465781f..16d87f0 100644 --- a/src/Validator.php +++ b/src/Validator.php @@ -21,1657 +21,1657 @@ */ class Validator { - /** - * @var string - */ - const ERROR_DEFAULT = 'Invalid'; - - /** - * @var array - */ - protected $_fields = array(); - - /** - * @var array - */ - protected $_errors = array(); - - /** - * @var array - */ - protected $_validations = array(); - - /** - * @var array - */ - protected $_labels = array(); - - /** - * Contains all rules that are available to the current valitron instance. - * - * @var array - */ - protected $_instanceRules = array(); - - /** - * Contains all rule messages that are available to the current valitron - * instance - * - * @var array - */ - protected $_instanceRuleMessage = array(); - - /** - * @var string - */ - protected static $_lang; - - /** - * @var string - */ - protected static $_langDir; - - /** - * @var array - */ - protected static $_rules = array(); - - /** - * @var array - */ - protected static $_ruleMessages = array(); - - /** - * @var array - */ - protected $validUrlPrefixes = array('http://', 'https://', 'ftp://'); - - /** - * @var bool - */ - protected $stop_on_first_fail = false; - - /** - * @var bool - */ - protected $prepend_labels = true; - - /** - * Setup validation - * - * @param array $data - * @param array $fields - * @param string $lang - * @param string $langDir - * - * @throws \InvalidArgumentException - */ - public function __construct($data = array(), $fields = array(), $lang = null, $langDir = null) - { - // Allows filtering of used input fields against optional second array of field names allowed - // This is useful for limiting raw $_POST or $_GET data to only known fields - $this->_fields = ! empty($fields) ? array_intersect_key($data, array_flip($fields)) : $data; - - // set lang in the follow order: constructor param, static::$_lang, default to en - $lang = $lang ?: static::lang(); - - // set langDir in the follow order: constructor param, static::$_langDir, default to package lang dir - $langDir = $langDir ?: static::langDir(); - - // Load language file in directory - $langFile = rtrim($langDir, '/') . '/' . $lang . '.php'; - if (stream_resolve_include_path($langFile)) { - $langMessages = include $langFile; - static::$_ruleMessages = array_merge(static::$_ruleMessages, $langMessages); - } else { - throw new \InvalidArgumentException("Fail to load language file '" . $langFile . "'"); - } - } - - /** - * Get/set language to use for validation messages - * - * @param string $lang - * - * @return string - */ - public static function lang($lang = null) - { - if ($lang !== null) { - static::$_lang = $lang; - } - - return static::$_lang ?: 'en'; - } - - /** - * Get/set language file path - * - * @param string $dir - * - * @return string - */ - public static function langDir($dir = null) - { - if ($dir !== null) { - static::$_langDir = $dir; - } - - return static::$_langDir ?: __DIR__ . '/validator/lang'; - } - - /** - * @param bool $prepend_labels - */ - public function setPrependLabels($prepend_labels = true) - { - $this->prepend_labels = $prepend_labels; - } - - /** - * Required field validator - * - * @param string $field - * @param mixed $value - * @param array $params - * - * @return bool - */ - protected function validateRequired($field, $value, $params = array()) - { - if (isset($params[0]) && (bool)$params[0]) { - $find = $this->getPart($this->_fields, explode('.', $field), true); - - return $find[1]; - } - - if (is_null($value) || (is_string($value) && trim($value) === '')) { - return false; - } - - return true; - } - - /** - * Validate that two values match - * - * @param string $field - * @param mixed $value - * @param array $params - * - * @return bool - */ - protected function validateEquals($field, $value, array $params) - { - // extract the second field value, this accounts for nested array values - list($field2Value, $multiple) = $this->getPart($this->_fields, explode('.', $params[0])); - - return isset($field2Value) && $value == $field2Value; - } - - /** - * Validate that a field is different from another field - * - * @param string $field - * @param mixed $value - * @param array $params - * - * @return bool - */ - protected function validateDifferent($field, $value, array $params) - { - // extract the second field value, this accounts for nested array values - list($field2Value, $multiple) = $this->getPart($this->_fields, explode('.', $params[0])); - - return isset($field2Value) && $value != $field2Value; - } - - /** - * Validate that a field was "accepted" (based on PHP's string evaluation rules) - * - * This validation rule implies the field is "required" - * - * @param string $field - * @param mixed $value - * - * @return bool - */ - protected function validateAccepted($field, $value) - { - $acceptable = array('yes', 'on', 1, '1', true); - - return $this->validateRequired($field, $value) && in_array($value, $acceptable, true); - } - - /** - * Validate that a field is an array - * - * @param string $field - * @param mixed $value - * - * @return bool - */ - protected function validateArray($field, $value) - { - return is_array($value); - } - - /** - * Validate that a field is numeric - * - * @param string $field - * @param mixed $value - * - * @return bool - */ - protected function validateNumeric($field, $value) - { - return is_numeric($value); - } - - /** - * Validate that a field is an integer - * - * @param string $field - * @param mixed $value - * @param array $params - * - * @return bool - */ - protected function validateInteger($field, $value, $params) - { - if (isset($params[0]) && (bool)$params[0]) { - //strict mode - return preg_match('/^([0-9]|-[1-9]|-?[1-9][0-9]*)$/i', $value); - } - - return filter_var($value, \FILTER_VALIDATE_INT) !== false; - } - - /** - * Validate the length of a string - * - * @param string $field - * @param mixed $value - * @param array $params - * - * @return bool - */ - protected function validateLength($field, $value, $params) - { - $length = $this->stringLength($value); - // Length between - if (isset($params[1])) { - return $length >= $params[0] && $length <= $params[1]; - } - - // Length same - return ($length !== false) && $length == $params[0]; - } - - /** - * Validate the length of a string (between) - * - * @param string $field - * @param mixed $value - * @param array $params - * - * @return bool - */ - protected function validateLengthBetween($field, $value, $params) - { - $length = $this->stringLength($value); - - return ($length !== false) && $length >= $params[0] && $length <= $params[1]; - } - - /** - * Validate the length of a string (min) - * - * @param string $field - * @param mixed $value - * @param array $params - * - * @return bool - */ - protected function validateLengthMin($field, $value, $params) - { - $length = $this->stringLength($value); - - return ($length !== false) && $length >= $params[0]; - } - - /** - * Validate the length of a string (max) - * - * @param string $field - * @param mixed $value - * @param array $params - * - * @return bool - */ - protected function validateLengthMax($field, $value, $params) - { - $length = $this->stringLength($value); - - return ($length !== false) && $length <= $params[0]; - } - - /** - * Get the length of a string - * - * @param string $value - * - * @return int|false - */ - protected function stringLength($value) - { - if ( ! is_string($value)) { - return false; - } - - return mb_strlen($value); - } - - /** - * Validate the size of a field is greater than a minimum value. - * - * @param string $field - * @param mixed $value - * @param array $params - * - * @return bool - */ - protected function validateMin($field, $value, $params) - { - if ( ! is_numeric($value)) { - return false; - } - - if (function_exists('bccomp')) { - return ! (bccomp($params[0], $value, 14) === 1); - } - - return $params[0] <= $value; - } - - /** - * Validate the size of a field is less than a maximum value - * - * @param string $field - * @param mixed $value - * @param array $params - * - * @return bool - */ - protected function validateMax($field, $value, $params) - { - if ( ! is_numeric($value)) { - return false; - } elseif (function_exists('bccomp')) { - return ! (bccomp($value, $params[0], 14) === 1); - } else { - return $params[0] >= $value; - } - } - - /** - * Validate the size of a field is between min and max values - * - * @param string $field - * @param mixed $value - * @param array $params - * - * @return bool - */ - protected function validateBetween($field, $value, $params) - { - if ( ! is_numeric($value)) { - return false; - } - if ( ! isset($params[0]) || ! is_array($params[0]) || count($params[0]) !== 2) { - return false; - } - - list($min, $max) = $params[0]; - - return $this->validateMin($field, $value, array($min)) && $this->validateMax($field, $value, array($max)); - } - - /** - * Validate a field is contained within a list of values - * - * @param string $field - * @param mixed $value - * @param array $params - * - * @return bool - */ - protected function validateIn($field, $value, $params) - { - $forceAsAssociative = false; - if (isset($params[2])) { - $forceAsAssociative = (bool)$params[2]; - } - - if ($forceAsAssociative || $this->isAssociativeArray($params[0])) { - $params[0] = array_keys($params[0]); - } - - $strict = false; - if (isset($params[1])) { - $strict = $params[1]; - } - - return in_array($value, $params[0], $strict); - } - - /** - * Validate a field is contained within a list of values - * - * @param string $field - * @param mixed $value - * @param array $params - * - * @return bool - */ - protected function validateListContains($field, $value, $params) - { - $forceAsAssociative = false; - if (isset($params[2])) { - $forceAsAssociative = (bool)$params[2]; - } - - if ($forceAsAssociative || $this->isAssociativeArray($value)) { - $value = array_keys($value); - } - - $strict = false; - if (isset($params[1])) { - $strict = $params[1]; - } - - return in_array($params[0], $value, $strict); - } - - /** - * Validate a field is not contained within a list of values - * - * @param string $field - * @param mixed $value - * @param array $params - * - * @return bool - */ - protected function validateNotIn($field, $value, $params) - { - return ! $this->validateIn($field, $value, $params); - } - - /** - * Validate a field contains a given string - * - * @param string $field - * @param string $value - * @param array $params - * - * @return bool - */ - protected function validateContains($field, $value, $params) - { - if ( ! isset($params[0])) { - return false; - } - if ( ! is_string($params[0]) || ! is_string($value)) { - return false; - } - - $strict = true; - if (isset($params[1])) { - $strict = (bool)$params[1]; - } - - if ($strict) { - if (function_exists('mb_strpos')) { - $isContains = mb_strpos($value, $params[0]) !== false; - } else { - $isContains = strpos($value, $params[0]) !== false; - } - } elseif (function_exists('mb_stripos')) { - $isContains = mb_stripos($value, $params[0]) !== false; - } else { - $isContains = stripos($value, $params[0]) !== false; - } - - return $isContains; - } - - /** - * Validate that all field values contains a given array - * - * @param string $field - * @param array $value - * @param array $params - * - * @return bool - */ - protected function validateSubset($field, $value, $params) - { - if ( ! isset($params[0])) { - return false; - } - if ( ! is_array($params[0])) { - $params[0] = array($params[0]); - } - if (is_scalar($value) || is_null($value)) { - return $this->validateIn($field, $value, $params); - } - - $intersect = array_intersect($value, $params[0]); - - return array_diff($value, $intersect) === array_diff($intersect, $value); - } - - /** - * Validate that field array has only unique values - * - * @param string $field - * @param array $value - * - * @return bool - */ - protected function validateContainsUnique($field, $value) - { - if ( ! is_array($value)) { - return false; - } - - return $value === array_unique($value, SORT_REGULAR); - } - - /** - * Validate that a field is a valid IP address - * - * @param string $field - * @param mixed $value - * - * @return bool - */ - protected function validateIp($field, $value) - { - return filter_var($value, \FILTER_VALIDATE_IP) !== false; - } - - /** - * Validate that a field is a valid IP v4 address - * - * @param string $field - * @param mixed $value - * - * @return bool - */ - protected function validateIpv4($field, $value) - { - return filter_var($value, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV4) !== false; - } - - /** - * Validate that a field is a valid IP v6 address - * - * @param string $field - * @param mixed $value - * - * @return bool - */ - protected function validateIpv6($field, $value) - { - return filter_var($value, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV6) !== false; - } - - /** - * Validate that a field is a valid e-mail address - * - * @param string $field - * @param mixed $value - * - * @return bool - */ - protected function validateEmail($field, $value) - { - return filter_var($value, \FILTER_VALIDATE_EMAIL) !== false; - } - - /** - * Validate that a field contains only ASCII characters - * - * @param $field - * @param $value - * - * @return bool|false|string - */ - protected function validateAscii($field, $value) - { - // multibyte extension needed - if (function_exists('mb_detect_encoding')) { - return mb_detect_encoding($value, 'ASCII', true); - } - - // fallback with regex - return 0 === preg_match('/[^\x00-\x7F]/', $value); - } - - /** - * Validate that a field is a valid e-mail address and the domain name is active - * - * @param string $field - * @param mixed $value - * - * @return bool - */ - protected function validateEmailDNS($field, $value) - { - if ( ! is_string($value)) { - return false; - } - - if ($this->validateEmail($field, $value)) { - $domain = ltrim(stristr($value, '@'), '@') . '.'; - if (function_exists('idn_to_ascii') && defined('INTL_IDNA_VARIANT_UTS46')) { - $domain = idn_to_ascii($domain, 0, INTL_IDNA_VARIANT_UTS46); - } - - return checkdnsrr($domain, 'MX'); - } - - return false; - } - - /** - * Validate that a field is a valid URL by syntax - * - * @param string $field - * @param mixed $value - * - * @return bool - */ - protected function validateUrl($field, $value) - { - if ( ! is_string($value)) { - return false; - } - - foreach ($this->validUrlPrefixes as $prefix) { - if (mb_strpos($value, $prefix) !== false) { - return filter_var($value, \FILTER_VALIDATE_URL) !== false; - } - } - - return false; - } - - /** - * Validate that a field is an active URL by verifying DNS record - * - * @param string $field - * @param mixed $value - * - * @return bool - */ - protected function validateUrlActive($field, $value) - { - if ( ! is_string($value)) { - return false; - } - - foreach ($this->validUrlPrefixes as $prefix) { - if (mb_strpos($value, $prefix) !== false) { - $host = parse_url(mb_strtolower($value), PHP_URL_HOST); - - return checkdnsrr($host, 'A') || checkdnsrr($host, 'AAAA') || checkdnsrr($host, 'CNAME'); - } - } - - return false; - } - - /** - * Validate that a field contains only alphabetic characters - * - * @param string $field - * @param mixed $value - * - * @return bool - */ - protected function validateAlpha($field, $value) - { - return preg_match('/^([a-z])+$/i', $value); - } - - /** - * Validate that a field contains only alpha-numeric characters - * - * @param string $field - * @param mixed $value - * - * @return bool - */ - protected function validateAlphaNum($field, $value) - { - return preg_match('/^([a-z0-9])+$/i', $value); - } - - /** - * Validate that a field contains only alpha-numeric characters, dashes, and underscores - * - * @param string $field - * @param mixed $value - * - * @return bool - */ - protected function validateSlug($field, $value) - { - if (is_array($value)) { - return false; - } - - return preg_match('/^([-a-z0-9_-])+$/i', $value); - } - - /** - * Validate that a field passes a regular expression check - * - * @param string $field - * @param mixed $value - * @param array $params - * - * @return bool - */ - protected function validateRegex($field, $value, $params) - { - return preg_match($params[0], $value); - } - - /** - * Validate that a field is a valid date - * - * @param string $field - * @param mixed $value - * - * @return bool - */ - protected function validateDate($field, $value) - { - $isDate = false; - if ($value instanceof \DateTime) { - $isDate = true; - } else { - $isDate = strtotime($value) !== false; - } - - return $isDate; - } - - /** - * Validate that a field matches a date format - * - * @param string $field - * @param mixed $value - * @param array $params - * - * @return bool - */ - protected function validateDateFormat($field, $value, $params) - { - $parsed = date_parse_from_format($params[0], $value); - - return $parsed['error_count'] === 0 && $parsed['warning_count'] === 0; - } - - /** - * Validate the date is before a given date - * - * @param string $field - * @param mixed $value - * @param array $params - * - * @return bool - */ - protected function validateDateBefore($field, $value, $params) - { - $vtime = ($value instanceof \DateTime) ? $value->getTimestamp() : strtotime($value); - $ptime = ($params[0] instanceof \DateTime) ? $params[0]->getTimestamp() : strtotime($params[0]); - - return $vtime < $ptime; - } - - /** - * Validate the date is after a given date - * - * @param string $field - * @param mixed $value - * @param array $params - * - * @return bool - */ - protected function validateDateAfter($field, $value, $params) - { - $vtime = ($value instanceof \DateTime) ? $value->getTimestamp() : strtotime($value); - $ptime = ($params[0] instanceof \DateTime) ? $params[0]->getTimestamp() : strtotime($params[0]); - - return $vtime > $ptime; - } - - /** - * Validate that a field contains a boolean. - * - * @param string $field - * @param mixed $value - * - * @return bool - */ - protected function validateBoolean($field, $value) - { - return is_bool($value); - } - - /** - * Validate that a field contains a valid credit card - * optionally filtered by an array - * - * @param string $field - * @param mixed $value - * @param array $params - * - * @return bool - */ - protected function validateCreditCard($field, $value, $params) - { - /** - * I there has been an array of valid cards supplied, or the name of the users card - * or the name and an array of valid cards - */ - if ( ! empty($params)) { - /** - * array of valid cards - */ - if (is_array($params[0])) { - $cards = $params[0]; - } elseif (is_string($params[0])) { - $cardType = $params[0]; - if (isset($params[1]) && is_array($params[1])) { - $cards = $params[1]; - if ( ! in_array($cardType, $cards)) { - return false; - } - } - } - } - /** - * Luhn algorithm - * - * @return bool - */ - $numberIsValid = function () use ($value) { - $number = preg_replace('/[^0-9]+/', '', $value); - $sum = 0; - - $strlen = mb_strlen($number); - if ($strlen < 13) { - return false; - } - for ($i = 0; $i < $strlen; $i++) { - $digit = (int)mb_substr($number, $strlen - $i - 1, 1); - if ($i % 2 == 1) { - $sub_total = $digit * 2; - if ($sub_total > 9) { - $sub_total = ($sub_total - 10) + 1; - } - } else { - $sub_total = $digit; - } - $sum += $sub_total; - } - if ($sum > 0 && $sum % 10 == 0) { - return true; - } - - return false; - }; - - if ($numberIsValid()) { - if ( ! isset($cards)) { - return true; - } else { - $cardRegex = array( - 'visa' => '#^4[0-9]{12}(?:[0-9]{3})?$#', - 'mastercard' => '#^(5[1-5]|2[2-7])[0-9]{14}$#', - 'amex' => '#^3[47][0-9]{13}$#', - 'dinersclub' => '#^3(?:0[0-5]|[68][0-9])[0-9]{11}$#', - 'discover' => '#^6(?:011|5[0-9]{2})[0-9]{12}$#', - ); - - if (isset($cardType)) { - // if we don't have any valid cards specified and the card we've been given isn't in our regex array - if ( ! isset($cards) && ! in_array($cardType, array_keys($cardRegex))) { - return false; - } - - // we only need to test against one card type - return (preg_match($cardRegex[$cardType], $value) === 1); - } elseif (isset($cards)) { - // if we have cards, check our users card against only the ones we have - foreach ($cards as $card) { - if (in_array($card, array_keys($cardRegex)) && preg_match($cardRegex[$card], $value) === 1) { - // if the card is valid, we want to stop looping - return true; - } - } - } else { - // loop through every card - foreach ($cardRegex as $regex) { - // until we find a valid one - if (preg_match($regex, $value) === 1) { - return true; - } - } - } - } - } - - // if we've got this far, the card has passed no validation so it's invalid! - return false; - } - - protected function validateInstanceOf($field, $value, $params) - { - $isInstanceOf = false; - if (is_object($value)) { - if (is_object($params[0]) && $value instanceof $params[0]) { - $isInstanceOf = true; - } - if (get_class($value) === $params[0]) { - $isInstanceOf = true; - } - } - if (is_string($value)) { - if (is_string($params[0]) && get_class($value) === $params[0]) { - $isInstanceOf = true; - } - } - - return $isInstanceOf; - } - - /** - * Validates whether or not a field is required based on whether or not other fields are present. - * - * @param string $field name of the field in the data array - * @param mixed $value value of this field - * @param array $params parameters for this rule - * @param array $fields full list of data to be validated - * - * @return bool - */ - protected function validateRequiredWith($field, $value, $params, $fields) - { - $conditionallyReq = false; - // if we actually have conditionally required with fields to check against - if (isset($params[0])) { - // convert single value to array if it isn't already - $reqParams = is_array($params[0]) ? $params[0] : array($params[0]); - // check for the flag indicating if all fields are required - $allRequired = isset($params[1]) && (bool)$params[1]; - $emptyFields = 0; - foreach ($reqParams as $requiredField) { - // check the field is set, not null, and not the empty string - list($requiredFieldValue, $multiple) = $this->getPart($fields, explode('.', $requiredField)); - if (isset($requiredFieldValue) && ( ! is_string($requiredFieldValue) || trim( - $requiredFieldValue - ) !== '')) { - if ( ! $allRequired) { - $conditionallyReq = true; - break; - } else { - $emptyFields++; - } - } - } - // if all required fields are present in strict mode, we're requiring it - if ($allRequired && $emptyFields === count($reqParams)) { - $conditionallyReq = true; - } - } - // if we have conditionally required fields - if ($conditionallyReq && (is_null($value) || (is_string($value) && trim($value) === ''))) { - return false; - } - - return true; - } - - /** - * Validates whether or not a field is required based on whether or not other fields are present. - * - * @param string $field name of the field in the data array - * @param mixed $value value of this field - * @param array $params parameters for this rule - * @param array $fields full list of data to be validated - * - * @return bool - */ - protected function validateRequiredWithout($field, $value, $params, $fields) - { - $conditionallyReq = false; - // if we actually have conditionally required with fields to check against - if (isset($params[0])) { - // convert single value to array if it isn't already - $reqParams = is_array($params[0]) ? $params[0] : array($params[0]); - // check for the flag indicating if all fields are required - $allEmpty = isset($params[1]) && (bool)$params[1]; - $filledFields = 0; - foreach ($reqParams as $requiredField) { - // check the field is NOT set, null, or the empty string, in which case we are requiring this value be present - list($requiredFieldValue, $multiple) = $this->getPart($fields, explode('.', $requiredField)); - if ( ! isset($requiredFieldValue) || (is_string($requiredFieldValue) && trim( - $requiredFieldValue - ) === '')) { - if ( ! $allEmpty) { - $conditionallyReq = true; - break; - } else { - $filledFields++; - } - } - } - // if all fields were empty, then we're requiring this in strict mode - if ($allEmpty && $filledFields === count($reqParams)) { - $conditionallyReq = true; - } - } - // if we have conditionally required fields - if ($conditionallyReq && (is_null($value) || (is_string($value) && trim($value) === ''))) { - return false; - } - - return true; - } - - /** - * Validate optional field - * - * @param $field - * @param $value - * @param $params - * - * @return bool - */ - protected function validateOptional($field, $value, $params) - { - //Always return true - return true; - } - - protected function validateArrayHasKeys($field, $value, $params) - { - if ( ! is_array($value) || ! isset($params[0])) { - return false; - } - $requiredFields = $params[0]; - if (count($requiredFields) === 0) { - return false; - } - foreach ($requiredFields as $fieldName) { - if ( ! array_key_exists($fieldName, $value)) { - return false; - } - } - - return true; - } - - /** - * Get array of fields and data - * - * @return array - */ - public function data() - { - return $this->_fields; - } - - /** - * Get array of error messages - * - * @param null|string $field - * - * @return array|bool - */ - public function errors($field = null) - { - if ($field !== null) { - return isset($this->_errors[$field]) ? $this->_errors[$field] : false; - } - - return $this->_errors; - } - - /** - * Add an error to error messages array - * - * @param string $field - * @param string $message - * @param array $params - */ - public function error($field, $message, array $params = array()) - { - $message = $this->checkAndSetLabel($field, $message, $params); - - $values = array(); - // Printed values need to be in string format - foreach ($params as $param) { - if (is_array($param)) { - $param = "['" . implode("', '", $param) . "']"; - } - if ($param instanceof \DateTime) { - $param = $param->format('Y-m-d'); - } else { - if (is_object($param)) { - $param = get_class($param); - } - } - // Use custom label instead of field name if set - if (is_string($params[0]) && isset($this->_labels[$param])) { - $param = $this->_labels[$param]; - } - $values[] = $param; - } - - $this->_errors[$field][] = vsprintf($message, $values); - } - - /** - * Specify validation message to use for error for the last validation rule - * - * @param string $message - * - * @return Validator - */ - public function message($message) - { - $this->_validations[count($this->_validations) - 1]['message'] = $message; - - return $this; - } - - /** - * Reset object properties - */ - public function reset() - { - $this->_fields = array(); - $this->_errors = array(); - $this->_validations = array(); - $this->_labels = array(); - } - - protected function getPart($data, $identifiers, $allow_empty = false) - { - // Catches the case where the field is an array of discrete values - if (is_array($identifiers) && count($identifiers) === 0) { - return array($data, false); - } - // Catches the case where the data isn't an array or object - if (is_scalar($data)) { - return array(null, false); - } - $identifier = array_shift($identifiers); - // Glob match - if ($identifier === '*') { - $values = array(); - foreach ($data as $row) { - list($value, $multiple) = $this->getPart($row, $identifiers, $allow_empty); - if ($multiple) { - $values = array_merge($values, $value); - } else { - $values[] = $value; - } - } - - return array($values, true); - } // Dead end, abort - elseif ($identifier === null || ! isset($data[$identifier])) { - if ($allow_empty) { - //when empty values are allowed, we only care if the key exists - return array(null, array_key_exists($identifier, $data)); - } - - return array(null, false); - } // Match array element - elseif (count($identifiers) === 0) { - if ($allow_empty) { - //when empty values are allowed, we only care if the key exists - return array(null, array_key_exists($identifier, $data)); - } - - return array($data[$identifier], $allow_empty); - } // We need to go deeper - else { - return $this->getPart($data[$identifier], $identifiers, $allow_empty); - } - } - - private function validationMustBeExcecuted($validation, $field, $values, $multiple) - { - //always excecute requiredWith(out) rules - if (in_array($validation['rule'], array('requiredWith', 'requiredWithout'))) { - return true; - } - - //do not execute if the field is optional and not set - if ($this->hasRule('optional', $field) && ! isset($values)) { - return false; - } - - //ignore empty input, except for required and accepted rule - if ( ! $this->hasRule('required', $field) && ! in_array($validation['rule'], array('required', 'accepted'))) { - if ($multiple) { - return count($values) != 0; - } - - return (isset($values) && $values !== ''); - } - - return true; - } - - /** - * Run validations and return boolean result - * - * @return bool - */ - public function validate() - { - $set_to_break = false; - foreach ($this->_validations as $v) { - foreach ($v['fields'] as $field) { - list($values, $multiple) = $this->getPart($this->_fields, explode('.', $field), false); - - if ( ! $this->validationMustBeExcecuted($v, $field, $values, $multiple)) { - continue; - } - - // Callback is user-specified or assumed method on class - $errors = $this->getRules(); - if (isset($errors[$v['rule']])) { - $callback = $errors[$v['rule']]; - } else { - $callback = array($this, 'validate' . ucfirst($v['rule'])); - } - - if ( ! $multiple) { - $values = array($values); - } elseif ( ! $this->hasRule('required', $field)) { - $values = array_filter($values); - } - - $result = true; - foreach ($values as $value) { - $result = $result && call_user_func($callback, $field, $value, $v['params'], $this->_fields); - } - - if ( ! $result) { - $this->error($field, $v['message'], $v['params']); - if ($this->stop_on_first_fail) { - $set_to_break = true; - break; - } - } - } - if ($set_to_break) { - break; - } - } - - return count($this->errors()) === 0; - } - - /** - * Should the validation stop a rule is failed - * - * @param bool $stop - */ - public function stopOnFirstFail($stop = true) - { - $this->stop_on_first_fail = (bool)$stop; - } - - /** - * Returns all rule callbacks, the static and instance ones. - * - * @return array - */ - protected function getRules() - { - return array_merge($this->_instanceRules, static::$_rules); - } - - /** - * Returns all rule message, the static and instance ones. - * - * @return array - */ - protected function getRuleMessages() - { - return array_merge($this->_instanceRuleMessage, static::$_ruleMessages); - } - - /** - * Determine whether a field is being validated by the given rule. - * - * @param string $name The name of the rule - * @param string $field The name of the field - * - * @return bool - */ - protected function hasRule($name, $field) - { - foreach ($this->_validations as $validation) { - if ($validation['rule'] == $name && in_array($field, $validation['fields'])) { - return true; - } - } - - return false; - } - - protected static function assertRuleCallback($callback) - { - if ( ! is_callable($callback)) { - throw new \InvalidArgumentException( - 'Second argument must be a valid callback. Given argument was not callable.' - ); - } - } - - /** - * Adds a new validation rule callback that is tied to the current - * instance only. - * - * @param string $name - * @param callable $callback - * @param string $message - * - * @throws \InvalidArgumentException - */ - public function addInstanceRule($name, $callback, $message = null) - { - static::assertRuleCallback($callback); - - $this->_instanceRules[$name] = $callback; - $this->_instanceRuleMessage[$name] = $message; - } - - /** - * Register new validation rule callback - * - * @param string $name - * @param callable $callback - * @param string $message - * - * @throws \InvalidArgumentException - */ - public static function addRule($name, $callback, $message = null) - { - if ($message === null) { - $message = static::ERROR_DEFAULT; - } - - static::assertRuleCallback($callback); - - static::$_rules[$name] = $callback; - static::$_ruleMessages[$name] = $message; - } - - /** - * @param mixed $fields - * - * @return string - */ - public function getUniqueRuleName($fields) - { - if (is_array($fields)) { - $fields = implode("_", $fields); - } - - $orgName = "{$fields}_rule"; - $name = $orgName; - $rules = $this->getRules(); - while (isset($rules[$name])) { - $name = $orgName . "_" . rand(0, 10000); - } - - return $name; - } - - /** - * Returns true if either a validator with the given name has been - * registered or there is a default validator by that name. - * - * @param string $name - * - * @return bool - */ - public function hasValidator($name) - { - $rules = $this->getRules(); - - return method_exists($this, "validate" . ucfirst($name)) - || isset($rules[$name]); - } - - /** - * Convenience method to add a single validation rule - * - * @param string|callable $rule - * @param array|string $fields - * - * @return Validator - * @throws \InvalidArgumentException - */ - public function rule($rule, $fields) - { - // Get any other arguments passed to function - $params = array_slice(func_get_args(), 2); - - if (is_callable($rule) - && ! (is_string($rule) && $this->hasValidator($rule))) { - $name = $this->getUniqueRuleName($fields); - $message = isset($params[0]) ? $params[0] : null; - $this->addInstanceRule($name, $rule, $message); - $rule = $name; - } - - $errors = $this->getRules(); - if ( ! isset($errors[$rule])) { - $ruleMethod = 'validate' . ucfirst($rule); - if ( ! method_exists($this, $ruleMethod)) { - throw new \InvalidArgumentException( - "Rule '" . $rule . "' has not been registered with " . get_called_class() . "::addRule()." - ); - } - } - - // Ensure rule has an accompanying message - $messages = $this->getRuleMessages(); - $message = isset($messages[$rule]) ? $messages[$rule] : self::ERROR_DEFAULT; - - // Ensure message contains field label - if (function_exists('mb_strpos')) { - $notContains = mb_strpos($message, '{field}') === false; - } else { - $notContains = strpos($message, '{field}') === false; - } - if ($notContains) { - $message = '{field} ' . $message; - } - - $this->_validations[] = array( - 'rule' => $rule, - 'fields' => (array)$fields, - 'params' => (array)$params, - 'message' => $message - ); - - return $this; - } - - /** - * Add label to rule - * - * @param string $value - * - * @return Validator - */ - public function label($value) - { - $lastRules = $this->_validations[count($this->_validations) - 1]['fields']; - $this->labels(array($lastRules[0] => $value)); - - return $this; - } - - /** - * Add labels to rules - * - * @param array $labels - * - * @return Validator - */ - public function labels($labels = array()) - { - $this->_labels = array_merge($this->_labels, $labels); - - return $this; - } - - /** - * @param string $field - * @param string $message - * @param array $params - * - * @return array - */ - protected function checkAndSetLabel($field, $message, $params) - { - if (isset($this->_labels[$field])) { - $message = str_replace('{field}', $this->_labels[$field], $message); - - if (is_array($params)) { - $i = 1; - foreach ($params as $k => $v) { - $tag = '{field' . $i . '}'; - $label = isset($params[$k]) && (is_numeric($params[$k]) || is_string( - $params[$k] - )) && isset($this->_labels[$params[$k]]) ? $this->_labels[$params[$k]] : $tag; - $message = str_replace($tag, $label, $message); - $i++; - } - } - } else { - $message = $this->prepend_labels - ? str_replace('{field}', ucwords(str_replace('_', ' ', $field)), $message) - : str_replace('{field} ', '', $message); - } - - return $message; - } - - /** - * Convenience method to add multiple validation rules with an array - * - * @param array $rules - */ - public function rules($rules) - { - foreach ($rules as $ruleType => $params) { - if (is_array($params)) { - foreach ($params as $innerParams) { - if ( ! is_array($innerParams)) { - $innerParams = (array)$innerParams; - } - array_unshift($innerParams, $ruleType); - call_user_func_array(array($this, 'rule'), $innerParams); - } - } else { - $this->rule($ruleType, $params); - } - } - } - - /** - * Replace data on cloned instance - * - * @param array $data - * @param array $fields - * - * @return Validator - */ - public function withData($data, $fields = array()) - { - $clone = clone $this; - $clone->_fields = ! empty($fields) ? array_intersect_key($data, array_flip($fields)) : $data; - $clone->_errors = array(); - - return $clone; - } - - /** - * Convenience method to add validation rule(s) by field - * - * @param string $field - * @param array $rules - */ - public function mapFieldRules($field, $rules) - { - $me = $this; - - array_map(function ($rule) use ($field, $me) { - //rule must be an array - $rule = (array)$rule; - - //First element is the name of the rule - $ruleName = array_shift($rule); - - //find a custom message, if any - $message = null; - if (isset($rule['message'])) { - $message = $rule['message']; - unset($rule['message']); - } - //Add the field and additional parameters to the rule - $added = call_user_func_array(array($me, 'rule'), array_merge(array($ruleName, $field), $rule)); - if ( ! empty($message)) { - $added->message($message); - } - }, (array)$rules); - } - - /** - * Convenience method to add validation rule(s) for multiple fields - * - * @param array $rules - */ - public function mapFieldsRules($rules) - { - $me = $this; - array_map(function ($field) use ($rules, $me) { - $me->mapFieldRules($field, $rules[$field]); - }, array_keys($rules)); - } - - private function isAssociativeArray($input) - { - //array contains at least one key that's not an can not be cast to an integer - return count(array_filter(array_keys($input), 'is_string')) > 0; - } + /** + * @var string + */ + const ERROR_DEFAULT = 'Invalid'; + + /** + * @var array + */ + protected $_fields = array(); + + /** + * @var array + */ + protected $_errors = array(); + + /** + * @var array + */ + protected $_validations = array(); + + /** + * @var array + */ + protected $_labels = array(); + + /** + * Contains all rules that are available to the current valitron instance. + * + * @var array + */ + protected $_instanceRules = array(); + + /** + * Contains all rule messages that are available to the current valitron + * instance + * + * @var array + */ + protected $_instanceRuleMessage = array(); + + /** + * @var string + */ + protected static $_lang; + + /** + * @var string + */ + protected static $_langDir; + + /** + * @var array + */ + protected static $_rules = array(); + + /** + * @var array + */ + protected static $_ruleMessages = array(); + + /** + * @var array + */ + protected $validUrlPrefixes = array('http://', 'https://', 'ftp://'); + + /** + * @var bool + */ + protected $stop_on_first_fail = false; + + /** + * @var bool + */ + protected $prepend_labels = true; + + /** + * Setup validation + * + * @param array $data + * @param array $fields + * @param string $lang + * @param string $langDir + * + * @throws \InvalidArgumentException + */ + public function __construct($data = array(), $fields = array(), $lang = null, $langDir = null) + { + // Allows filtering of used input fields against optional second array of field names allowed + // This is useful for limiting raw $_POST or $_GET data to only known fields + $this->_fields = !empty($fields) ? array_intersect_key($data, array_flip($fields)) : $data; + + // set lang in the follow order: constructor param, static::$_lang, default to en + $lang = $lang ?: static::lang(); + + // set langDir in the follow order: constructor param, static::$_langDir, default to package lang dir + $langDir = $langDir ?: static::langDir(); + + // Load language file in directory + $langFile = rtrim($langDir, '/') . '/' . $lang . '.php'; + if (stream_resolve_include_path($langFile)) { + $langMessages = include $langFile; + static::$_ruleMessages = array_merge(static::$_ruleMessages, $langMessages); + } else { + throw new \InvalidArgumentException("Fail to load language file '" . $langFile . "'"); + } + } + + /** + * Get/set language to use for validation messages + * + * @param string $lang + * + * @return string + */ + public static function lang($lang = null) + { + if ($lang !== null) { + static::$_lang = $lang; + } + + return static::$_lang ?: 'en'; + } + + /** + * Get/set language file path + * + * @param string $dir + * + * @return string + */ + public static function langDir($dir = null) + { + if ($dir !== null) { + static::$_langDir = $dir; + } + + return static::$_langDir ?: __DIR__ . '/validator/lang'; + } + + /** + * @param bool $prepend_labels + */ + public function setPrependLabels($prepend_labels = true) + { + $this->prepend_labels = $prepend_labels; + } + + /** + * Required field validator + * + * @param string $field + * @param mixed $value + * @param array $params + * + * @return bool + */ + protected function validateRequired($field, $value, $params = array()) + { + if (isset($params[0]) && (bool)$params[0]) { + $find = $this->getPart($this->_fields, explode('.', $field), true); + + return $find[1]; + } + + if (is_null($value) || (is_string($value) && trim($value) === '')) { + return false; + } + + return true; + } + + /** + * Validate that two values match + * + * @param string $field + * @param mixed $value + * @param array $params + * + * @return bool + */ + protected function validateEquals($field, $value, array $params) + { + // extract the second field value, this accounts for nested array values + list($field2Value, $multiple) = $this->getPart($this->_fields, explode('.', $params[0])); + + return isset($field2Value) && $value == $field2Value; + } + + /** + * Validate that a field is different from another field + * + * @param string $field + * @param mixed $value + * @param array $params + * + * @return bool + */ + protected function validateDifferent($field, $value, array $params) + { + // extract the second field value, this accounts for nested array values + list($field2Value, $multiple) = $this->getPart($this->_fields, explode('.', $params[0])); + + return isset($field2Value) && $value != $field2Value; + } + + /** + * Validate that a field was "accepted" (based on PHP's string evaluation rules) + * + * This validation rule implies the field is "required" + * + * @param string $field + * @param mixed $value + * + * @return bool + */ + protected function validateAccepted($field, $value) + { + $acceptable = array('yes', 'on', 1, '1', true); + + return $this->validateRequired($field, $value) && in_array($value, $acceptable, true); + } + + /** + * Validate that a field is an array + * + * @param string $field + * @param mixed $value + * + * @return bool + */ + protected function validateArray($field, $value) + { + return is_array($value); + } + + /** + * Validate that a field is numeric + * + * @param string $field + * @param mixed $value + * + * @return bool + */ + protected function validateNumeric($field, $value) + { + return is_numeric($value); + } + + /** + * Validate that a field is an integer + * + * @param string $field + * @param mixed $value + * @param array $params + * + * @return bool + */ + protected function validateInteger($field, $value, $params) + { + if (isset($params[0]) && (bool)$params[0]) { + //strict mode + return preg_match('/^([0-9]|-[1-9]|-?[1-9][0-9]*)$/i', $value); + } + + return filter_var($value, \FILTER_VALIDATE_INT) !== false; + } + + /** + * Validate the length of a string + * + * @param string $field + * @param mixed $value + * @param array $params + * + * @return bool + */ + protected function validateLength($field, $value, $params) + { + $length = $this->stringLength($value); + // Length between + if (isset($params[1])) { + return $length >= $params[0] && $length <= $params[1]; + } + + // Length same + return ($length !== false) && $length == $params[0]; + } + + /** + * Validate the length of a string (between) + * + * @param string $field + * @param mixed $value + * @param array $params + * + * @return bool + */ + protected function validateLengthBetween($field, $value, $params) + { + $length = $this->stringLength($value); + + return ($length !== false) && $length >= $params[0] && $length <= $params[1]; + } + + /** + * Validate the length of a string (min) + * + * @param string $field + * @param mixed $value + * @param array $params + * + * @return bool + */ + protected function validateLengthMin($field, $value, $params) + { + $length = $this->stringLength($value); + + return ($length !== false) && $length >= $params[0]; + } + + /** + * Validate the length of a string (max) + * + * @param string $field + * @param mixed $value + * @param array $params + * + * @return bool + */ + protected function validateLengthMax($field, $value, $params) + { + $length = $this->stringLength($value); + + return ($length !== false) && $length <= $params[0]; + } + + /** + * Get the length of a string + * + * @param string $value + * + * @return int|false + */ + protected function stringLength($value) + { + if (!is_string($value)) { + return false; + } + + return mb_strlen($value); + } + + /** + * Validate the size of a field is greater than a minimum value. + * + * @param string $field + * @param mixed $value + * @param array $params + * + * @return bool + */ + protected function validateMin($field, $value, $params) + { + if (!is_numeric($value)) { + return false; + } + + if (function_exists('bccomp')) { + return !(bccomp($params[0], $value, 14) === 1); + } + + return $params[0] <= $value; + } + + /** + * Validate the size of a field is less than a maximum value + * + * @param string $field + * @param mixed $value + * @param array $params + * + * @return bool + */ + protected function validateMax($field, $value, $params) + { + if (!is_numeric($value)) { + return false; + } elseif (function_exists('bccomp')) { + return !(bccomp($value, $params[0], 14) === 1); + } else { + return $params[0] >= $value; + } + } + + /** + * Validate the size of a field is between min and max values + * + * @param string $field + * @param mixed $value + * @param array $params + * + * @return bool + */ + protected function validateBetween($field, $value, $params) + { + if (!is_numeric($value)) { + return false; + } + if (!isset($params[0]) || !is_array($params[0]) || count($params[0]) !== 2) { + return false; + } + + list($min, $max) = $params[0]; + + return $this->validateMin($field, $value, array($min)) && $this->validateMax($field, $value, array($max)); + } + + /** + * Validate a field is contained within a list of values + * + * @param string $field + * @param mixed $value + * @param array $params + * + * @return bool + */ + protected function validateIn($field, $value, $params) + { + $forceAsAssociative = false; + if (isset($params[2])) { + $forceAsAssociative = (bool)$params[2]; + } + + if ($forceAsAssociative || $this->isAssociativeArray($params[0])) { + $params[0] = array_keys($params[0]); + } + + $strict = false; + if (isset($params[1])) { + $strict = $params[1]; + } + + return in_array($value, $params[0], $strict); + } + + /** + * Validate a field is contained within a list of values + * + * @param string $field + * @param mixed $value + * @param array $params + * + * @return bool + */ + protected function validateListContains($field, $value, $params) + { + $forceAsAssociative = false; + if (isset($params[2])) { + $forceAsAssociative = (bool)$params[2]; + } + + if ($forceAsAssociative || $this->isAssociativeArray($value)) { + $value = array_keys($value); + } + + $strict = false; + if (isset($params[1])) { + $strict = $params[1]; + } + + return in_array($params[0], $value, $strict); + } + + /** + * Validate a field is not contained within a list of values + * + * @param string $field + * @param mixed $value + * @param array $params + * + * @return bool + */ + protected function validateNotIn($field, $value, $params) + { + return !$this->validateIn($field, $value, $params); + } + + /** + * Validate a field contains a given string + * + * @param string $field + * @param string $value + * @param array $params + * + * @return bool + */ + protected function validateContains($field, $value, $params) + { + if (!isset($params[0])) { + return false; + } + if (!is_string($params[0]) || !is_string($value)) { + return false; + } + + $strict = true; + if (isset($params[1])) { + $strict = (bool)$params[1]; + } + + if ($strict) { + if (function_exists('mb_strpos')) { + $isContains = mb_strpos($value, $params[0]) !== false; + } else { + $isContains = strpos($value, $params[0]) !== false; + } + } elseif (function_exists('mb_stripos')) { + $isContains = mb_stripos($value, $params[0]) !== false; + } else { + $isContains = stripos($value, $params[0]) !== false; + } + + return $isContains; + } + + /** + * Validate that all field values contains a given array + * + * @param string $field + * @param array $value + * @param array $params + * + * @return bool + */ + protected function validateSubset($field, $value, $params) + { + if (!isset($params[0])) { + return false; + } + if (!is_array($params[0])) { + $params[0] = array($params[0]); + } + if (is_scalar($value) || is_null($value)) { + return $this->validateIn($field, $value, $params); + } + + $intersect = array_intersect($value, $params[0]); + + return array_diff($value, $intersect) === array_diff($intersect, $value); + } + + /** + * Validate that field array has only unique values + * + * @param string $field + * @param array $value + * + * @return bool + */ + protected function validateContainsUnique($field, $value) + { + if (!is_array($value)) { + return false; + } + + return $value === array_unique($value, SORT_REGULAR); + } + + /** + * Validate that a field is a valid IP address + * + * @param string $field + * @param mixed $value + * + * @return bool + */ + protected function validateIp($field, $value) + { + return filter_var($value, \FILTER_VALIDATE_IP) !== false; + } + + /** + * Validate that a field is a valid IP v4 address + * + * @param string $field + * @param mixed $value + * + * @return bool + */ + protected function validateIpv4($field, $value) + { + return filter_var($value, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV4) !== false; + } + + /** + * Validate that a field is a valid IP v6 address + * + * @param string $field + * @param mixed $value + * + * @return bool + */ + protected function validateIpv6($field, $value) + { + return filter_var($value, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV6) !== false; + } + + /** + * Validate that a field is a valid e-mail address + * + * @param string $field + * @param mixed $value + * + * @return bool + */ + protected function validateEmail($field, $value) + { + return filter_var($value, \FILTER_VALIDATE_EMAIL) !== false; + } + + /** + * Validate that a field contains only ASCII characters + * + * @param $field + * @param $value + * + * @return bool|false|string + */ + protected function validateAscii($field, $value) + { + // multibyte extension needed + if (function_exists('mb_detect_encoding')) { + return mb_detect_encoding($value, 'ASCII', true); + } + + // fallback with regex + return 0 === preg_match('/[^\x00-\x7F]/', $value); + } + + /** + * Validate that a field is a valid e-mail address and the domain name is active + * + * @param string $field + * @param mixed $value + * + * @return bool + */ + protected function validateEmailDNS($field, $value) + { + if (!is_string($value)) { + return false; + } + + if ($this->validateEmail($field, $value)) { + $domain = ltrim(stristr($value, '@'), '@') . '.'; + if (function_exists('idn_to_ascii') && defined('INTL_IDNA_VARIANT_UTS46')) { + $domain = idn_to_ascii($domain, 0, INTL_IDNA_VARIANT_UTS46); + } + + return checkdnsrr($domain, 'MX'); + } + + return false; + } + + /** + * Validate that a field is a valid URL by syntax + * + * @param string $field + * @param mixed $value + * + * @return bool + */ + protected function validateUrl($field, $value) + { + if (!is_string($value)) { + return false; + } + + foreach ($this->validUrlPrefixes as $prefix) { + if (mb_strpos($value, $prefix) !== false) { + return filter_var($value, \FILTER_VALIDATE_URL) !== false; + } + } + + return false; + } + + /** + * Validate that a field is an active URL by verifying DNS record + * + * @param string $field + * @param mixed $value + * + * @return bool + */ + protected function validateUrlActive($field, $value) + { + if (!is_string($value)) { + return false; + } + + foreach ($this->validUrlPrefixes as $prefix) { + if (mb_strpos($value, $prefix) !== false) { + $host = parse_url(mb_strtolower($value), PHP_URL_HOST); + + return checkdnsrr($host, 'A') || checkdnsrr($host, 'AAAA') || checkdnsrr($host, 'CNAME'); + } + } + + return false; + } + + /** + * Validate that a field contains only alphabetic characters + * + * @param string $field + * @param mixed $value + * + * @return bool + */ + protected function validateAlpha($field, $value) + { + return preg_match('/^([a-z])+$/i', $value); + } + + /** + * Validate that a field contains only alpha-numeric characters + * + * @param string $field + * @param mixed $value + * + * @return bool + */ + protected function validateAlphaNum($field, $value) + { + return preg_match('/^([a-z0-9])+$/i', $value); + } + + /** + * Validate that a field contains only alpha-numeric characters, dashes, and underscores + * + * @param string $field + * @param mixed $value + * + * @return bool + */ + protected function validateSlug($field, $value) + { + if (is_array($value)) { + return false; + } + + return preg_match('/^([-a-z0-9_-])+$/i', $value); + } + + /** + * Validate that a field passes a regular expression check + * + * @param string $field + * @param mixed $value + * @param array $params + * + * @return bool + */ + protected function validateRegex($field, $value, $params) + { + return preg_match($params[0], $value); + } + + /** + * Validate that a field is a valid date + * + * @param string $field + * @param mixed $value + * + * @return bool + */ + protected function validateDate($field, $value) + { + $isDate = false; + if ($value instanceof \DateTime) { + $isDate = true; + } else { + $isDate = strtotime($value) !== false; + } + + return $isDate; + } + + /** + * Validate that a field matches a date format + * + * @param string $field + * @param mixed $value + * @param array $params + * + * @return bool + */ + protected function validateDateFormat($field, $value, $params) + { + $parsed = date_parse_from_format($params[0], $value); + + return $parsed['error_count'] === 0 && $parsed['warning_count'] === 0; + } + + /** + * Validate the date is before a given date + * + * @param string $field + * @param mixed $value + * @param array $params + * + * @return bool + */ + protected function validateDateBefore($field, $value, $params) + { + $vtime = ($value instanceof \DateTime) ? $value->getTimestamp() : strtotime($value); + $ptime = ($params[0] instanceof \DateTime) ? $params[0]->getTimestamp() : strtotime($params[0]); + + return $vtime < $ptime; + } + + /** + * Validate the date is after a given date + * + * @param string $field + * @param mixed $value + * @param array $params + * + * @return bool + */ + protected function validateDateAfter($field, $value, $params) + { + $vtime = ($value instanceof \DateTime) ? $value->getTimestamp() : strtotime($value); + $ptime = ($params[0] instanceof \DateTime) ? $params[0]->getTimestamp() : strtotime($params[0]); + + return $vtime > $ptime; + } + + /** + * Validate that a field contains a boolean. + * + * @param string $field + * @param mixed $value + * + * @return bool + */ + protected function validateBoolean($field, $value) + { + return is_bool($value); + } + + /** + * Validate that a field contains a valid credit card + * optionally filtered by an array + * + * @param string $field + * @param mixed $value + * @param array $params + * + * @return bool + */ + protected function validateCreditCard($field, $value, $params) + { + /** + * I there has been an array of valid cards supplied, or the name of the users card + * or the name and an array of valid cards + */ + if (!empty($params)) { + /** + * array of valid cards + */ + if (is_array($params[0])) { + $cards = $params[0]; + } elseif (is_string($params[0])) { + $cardType = $params[0]; + if (isset($params[1]) && is_array($params[1])) { + $cards = $params[1]; + if (!in_array($cardType, $cards)) { + return false; + } + } + } + } + /** + * Luhn algorithm + * + * @return bool + */ + $numberIsValid = function () use ($value) { + $number = preg_replace('/[^0-9]+/', '', $value); + $sum = 0; + + $strlen = mb_strlen($number); + if ($strlen < 13) { + return false; + } + for ($i = 0; $i < $strlen; $i++) { + $digit = (int)mb_substr($number, $strlen - $i - 1, 1); + if ($i % 2 == 1) { + $sub_total = $digit * 2; + if ($sub_total > 9) { + $sub_total = ($sub_total - 10) + 1; + } + } else { + $sub_total = $digit; + } + $sum += $sub_total; + } + if ($sum > 0 && $sum % 10 == 0) { + return true; + } + + return false; + }; + + if ($numberIsValid()) { + if (!isset($cards)) { + return true; + } else { + $cardRegex = array( + 'visa' => '#^4[0-9]{12}(?:[0-9]{3})?$#', + 'mastercard' => '#^(5[1-5]|2[2-7])[0-9]{14}$#', + 'amex' => '#^3[47][0-9]{13}$#', + 'dinersclub' => '#^3(?:0[0-5]|[68][0-9])[0-9]{11}$#', + 'discover' => '#^6(?:011|5[0-9]{2})[0-9]{12}$#', + ); + + if (isset($cardType)) { + // if we don't have any valid cards specified and the card we've been given isn't in our regex array + if (!isset($cards) && !in_array($cardType, array_keys($cardRegex))) { + return false; + } + + // we only need to test against one card type + return (preg_match($cardRegex[$cardType], $value) === 1); + } elseif (isset($cards)) { + // if we have cards, check our users card against only the ones we have + foreach ($cards as $card) { + if (in_array($card, array_keys($cardRegex)) && preg_match($cardRegex[$card], $value) === 1) { + // if the card is valid, we want to stop looping + return true; + } + } + } else { + // loop through every card + foreach ($cardRegex as $regex) { + // until we find a valid one + if (preg_match($regex, $value) === 1) { + return true; + } + } + } + } + } + + // if we've got this far, the card has passed no validation so it's invalid! + return false; + } + + protected function validateInstanceOf($field, $value, $params) + { + $isInstanceOf = false; + if (is_object($value)) { + if (is_object($params[0]) && $value instanceof $params[0]) { + $isInstanceOf = true; + } + if (get_class($value) === $params[0]) { + $isInstanceOf = true; + } + } + if (is_string($value)) { + if (is_string($params[0]) && get_class($value) === $params[0]) { + $isInstanceOf = true; + } + } + + return $isInstanceOf; + } + + /** + * Validates whether or not a field is required based on whether or not other fields are present. + * + * @param string $field name of the field in the data array + * @param mixed $value value of this field + * @param array $params parameters for this rule + * @param array $fields full list of data to be validated + * + * @return bool + */ + protected function validateRequiredWith($field, $value, $params, $fields) + { + $conditionallyReq = false; + // if we actually have conditionally required with fields to check against + if (isset($params[0])) { + // convert single value to array if it isn't already + $reqParams = is_array($params[0]) ? $params[0] : array($params[0]); + // check for the flag indicating if all fields are required + $allRequired = isset($params[1]) && (bool)$params[1]; + $emptyFields = 0; + foreach ($reqParams as $requiredField) { + // check the field is set, not null, and not the empty string + list($requiredFieldValue, $multiple) = $this->getPart($fields, explode('.', $requiredField)); + if (isset($requiredFieldValue) && (!is_string($requiredFieldValue) || trim( + $requiredFieldValue + ) !== '')) { + if (!$allRequired) { + $conditionallyReq = true; + break; + } else { + $emptyFields++; + } + } + } + // if all required fields are present in strict mode, we're requiring it + if ($allRequired && $emptyFields === count($reqParams)) { + $conditionallyReq = true; + } + } + // if we have conditionally required fields + if ($conditionallyReq && (is_null($value) || (is_string($value) && trim($value) === ''))) { + return false; + } + + return true; + } + + /** + * Validates whether or not a field is required based on whether or not other fields are present. + * + * @param string $field name of the field in the data array + * @param mixed $value value of this field + * @param array $params parameters for this rule + * @param array $fields full list of data to be validated + * + * @return bool + */ + protected function validateRequiredWithout($field, $value, $params, $fields) + { + $conditionallyReq = false; + // if we actually have conditionally required with fields to check against + if (isset($params[0])) { + // convert single value to array if it isn't already + $reqParams = is_array($params[0]) ? $params[0] : array($params[0]); + // check for the flag indicating if all fields are required + $allEmpty = isset($params[1]) && (bool)$params[1]; + $filledFields = 0; + foreach ($reqParams as $requiredField) { + // check the field is NOT set, null, or the empty string, in which case we are requiring this value be present + list($requiredFieldValue, $multiple) = $this->getPart($fields, explode('.', $requiredField)); + if (!isset($requiredFieldValue) || (is_string($requiredFieldValue) && trim( + $requiredFieldValue + ) === '')) { + if (!$allEmpty) { + $conditionallyReq = true; + break; + } else { + $filledFields++; + } + } + } + // if all fields were empty, then we're requiring this in strict mode + if ($allEmpty && $filledFields === count($reqParams)) { + $conditionallyReq = true; + } + } + // if we have conditionally required fields + if ($conditionallyReq && (is_null($value) || (is_string($value) && trim($value) === ''))) { + return false; + } + + return true; + } + + /** + * Validate optional field + * + * @param $field + * @param $value + * @param $params + * + * @return bool + */ + protected function validateOptional($field, $value, $params) + { + //Always return true + return true; + } + + protected function validateArrayHasKeys($field, $value, $params) + { + if (!is_array($value) || !isset($params[0])) { + return false; + } + $requiredFields = $params[0]; + if (count($requiredFields) === 0) { + return false; + } + foreach ($requiredFields as $fieldName) { + if (!array_key_exists($fieldName, $value)) { + return false; + } + } + + return true; + } + + /** + * Get array of fields and data + * + * @return array + */ + public function data() + { + return $this->_fields; + } + + /** + * Get array of error messages + * + * @param null|string $field + * + * @return array|bool + */ + public function errors($field = null) + { + if ($field !== null) { + return isset($this->_errors[$field]) ? $this->_errors[$field] : false; + } + + return $this->_errors; + } + + /** + * Add an error to error messages array + * + * @param string $field + * @param string $message + * @param array $params + */ + public function error($field, $message, array $params = array()) + { + $message = $this->checkAndSetLabel($field, $message, $params); + + $values = array(); + // Printed values need to be in string format + foreach ($params as $param) { + if (is_array($param)) { + $param = "['" . implode("', '", $param) . "']"; + } + if ($param instanceof \DateTime) { + $param = $param->format('Y-m-d'); + } else { + if (is_object($param)) { + $param = get_class($param); + } + } + // Use custom label instead of field name if set + if (is_string($params[0]) && isset($this->_labels[$param])) { + $param = $this->_labels[$param]; + } + $values[] = $param; + } + + $this->_errors[$field][] = vsprintf($message, $values); + } + + /** + * Specify validation message to use for error for the last validation rule + * + * @param string $message + * + * @return Validator + */ + public function message($message) + { + $this->_validations[count($this->_validations) - 1]['message'] = $message; + + return $this; + } + + /** + * Reset object properties + */ + public function reset() + { + $this->_fields = array(); + $this->_errors = array(); + $this->_validations = array(); + $this->_labels = array(); + } + + protected function getPart($data, $identifiers, $allow_empty = false) + { + // Catches the case where the field is an array of discrete values + if (is_array($identifiers) && count($identifiers) === 0) { + return array($data, false); + } + // Catches the case where the data isn't an array or object + if (is_scalar($data)) { + return array(null, false); + } + $identifier = array_shift($identifiers); + // Glob match + if ($identifier === '*') { + $values = array(); + foreach ($data as $row) { + list($value, $multiple) = $this->getPart($row, $identifiers, $allow_empty); + if ($multiple) { + $values = array_merge($values, $value); + } else { + $values[] = $value; + } + } + + return array($values, true); + } // Dead end, abort + elseif ($identifier === null || !isset($data[$identifier])) { + if ($allow_empty) { + //when empty values are allowed, we only care if the key exists + return array(null, array_key_exists($identifier, $data)); + } + + return array(null, false); + } // Match array element + elseif (count($identifiers) === 0) { + if ($allow_empty) { + //when empty values are allowed, we only care if the key exists + return array(null, array_key_exists($identifier, $data)); + } + + return array($data[$identifier], $allow_empty); + } // We need to go deeper + else { + return $this->getPart($data[$identifier], $identifiers, $allow_empty); + } + } + + private function validationMustBeExcecuted($validation, $field, $values, $multiple) + { + //always excecute requiredWith(out) rules + if (in_array($validation['rule'], array('requiredWith', 'requiredWithout'))) { + return true; + } + + //do not execute if the field is optional and not set + if ($this->hasRule('optional', $field) && !isset($values)) { + return false; + } + + //ignore empty input, except for required and accepted rule + if (!$this->hasRule('required', $field) && !in_array($validation['rule'], array('required', 'accepted'))) { + if ($multiple) { + return count($values) != 0; + } + + return (isset($values) && $values !== ''); + } + + return true; + } + + /** + * Run validations and return boolean result + * + * @return bool + */ + public function validate() + { + $set_to_break = false; + foreach ($this->_validations as $v) { + foreach ($v['fields'] as $field) { + list($values, $multiple) = $this->getPart($this->_fields, explode('.', $field), false); + + if (!$this->validationMustBeExcecuted($v, $field, $values, $multiple)) { + continue; + } + + // Callback is user-specified or assumed method on class + $errors = $this->getRules(); + if (isset($errors[$v['rule']])) { + $callback = $errors[$v['rule']]; + } else { + $callback = array($this, 'validate' . ucfirst($v['rule'])); + } + + if (!$multiple) { + $values = array($values); + } elseif (!$this->hasRule('required', $field)) { + $values = array_filter($values); + } + + $result = true; + foreach ($values as $value) { + $result = $result && call_user_func($callback, $field, $value, $v['params'], $this->_fields); + } + + if (!$result) { + $this->error($field, $v['message'], $v['params']); + if ($this->stop_on_first_fail) { + $set_to_break = true; + break; + } + } + } + if ($set_to_break) { + break; + } + } + + return count($this->errors()) === 0; + } + + /** + * Should the validation stop a rule is failed + * + * @param bool $stop + */ + public function stopOnFirstFail($stop = true) + { + $this->stop_on_first_fail = (bool)$stop; + } + + /** + * Returns all rule callbacks, the static and instance ones. + * + * @return array + */ + protected function getRules() + { + return array_merge($this->_instanceRules, static::$_rules); + } + + /** + * Returns all rule message, the static and instance ones. + * + * @return array + */ + protected function getRuleMessages() + { + return array_merge($this->_instanceRuleMessage, static::$_ruleMessages); + } + + /** + * Determine whether a field is being validated by the given rule. + * + * @param string $name The name of the rule + * @param string $field The name of the field + * + * @return bool + */ + protected function hasRule($name, $field) + { + foreach ($this->_validations as $validation) { + if ($validation['rule'] == $name && in_array($field, $validation['fields'])) { + return true; + } + } + + return false; + } + + protected static function assertRuleCallback($callback) + { + if (!is_callable($callback)) { + throw new \InvalidArgumentException( + 'Second argument must be a valid callback. Given argument was not callable.' + ); + } + } + + /** + * Adds a new validation rule callback that is tied to the current + * instance only. + * + * @param string $name + * @param callable $callback + * @param string $message + * + * @throws \InvalidArgumentException + */ + public function addInstanceRule($name, $callback, $message = null) + { + static::assertRuleCallback($callback); + + $this->_instanceRules[$name] = $callback; + $this->_instanceRuleMessage[$name] = $message; + } + + /** + * Register new validation rule callback + * + * @param string $name + * @param callable $callback + * @param string $message + * + * @throws \InvalidArgumentException + */ + public static function addRule($name, $callback, $message = null) + { + if ($message === null) { + $message = static::ERROR_DEFAULT; + } + + static::assertRuleCallback($callback); + + static::$_rules[$name] = $callback; + static::$_ruleMessages[$name] = $message; + } + + /** + * @param mixed $fields + * + * @return string + */ + public function getUniqueRuleName($fields) + { + if (is_array($fields)) { + $fields = implode("_", $fields); + } + + $orgName = "{$fields}_rule"; + $name = $orgName; + $rules = $this->getRules(); + while (isset($rules[$name])) { + $name = $orgName . "_" . rand(0, 10000); + } + + return $name; + } + + /** + * Returns true if either a validator with the given name has been + * registered or there is a default validator by that name. + * + * @param string $name + * + * @return bool + */ + public function hasValidator($name) + { + $rules = $this->getRules(); + + return method_exists($this, "validate" . ucfirst($name)) + || isset($rules[$name]); + } + + /** + * Convenience method to add a single validation rule + * + * @param string|callable $rule + * @param array|string $fields + * + * @return Validator + * @throws \InvalidArgumentException + */ + public function rule($rule, $fields) + { + // Get any other arguments passed to function + $params = array_slice(func_get_args(), 2); + + if (is_callable($rule) + && !(is_string($rule) && $this->hasValidator($rule))) { + $name = $this->getUniqueRuleName($fields); + $message = isset($params[0]) ? $params[0] : null; + $this->addInstanceRule($name, $rule, $message); + $rule = $name; + } + + $errors = $this->getRules(); + if (!isset($errors[$rule])) { + $ruleMethod = 'validate' . ucfirst($rule); + if (!method_exists($this, $ruleMethod)) { + throw new \InvalidArgumentException( + "Rule '" . $rule . "' has not been registered with " . get_called_class() . "::addRule()." + ); + } + } + + // Ensure rule has an accompanying message + $messages = $this->getRuleMessages(); + $message = isset($messages[$rule]) ? $messages[$rule] : self::ERROR_DEFAULT; + + // Ensure message contains field label + if (function_exists('mb_strpos')) { + $notContains = mb_strpos($message, '{field}') === false; + } else { + $notContains = strpos($message, '{field}') === false; + } + if ($notContains) { + $message = '{field} ' . $message; + } + + $this->_validations[] = array( + 'rule' => $rule, + 'fields' => (array)$fields, + 'params' => (array)$params, + 'message' => $message + ); + + return $this; + } + + /** + * Add label to rule + * + * @param string $value + * + * @return Validator + */ + public function label($value) + { + $lastRules = $this->_validations[count($this->_validations) - 1]['fields']; + $this->labels(array($lastRules[0] => $value)); + + return $this; + } + + /** + * Add labels to rules + * + * @param array $labels + * + * @return Validator + */ + public function labels($labels = array()) + { + $this->_labels = array_merge($this->_labels, $labels); + + return $this; + } + + /** + * @param string $field + * @param string $message + * @param array $params + * + * @return array + */ + protected function checkAndSetLabel($field, $message, $params) + { + if (isset($this->_labels[$field])) { + $message = str_replace('{field}', $this->_labels[$field], $message); + + if (is_array($params)) { + $i = 1; + foreach ($params as $k => $v) { + $tag = '{field' . $i . '}'; + $label = isset($params[$k]) && (is_numeric($params[$k]) || is_string( + $params[$k] + )) && isset($this->_labels[$params[$k]]) ? $this->_labels[$params[$k]] : $tag; + $message = str_replace($tag, $label, $message); + $i++; + } + } + } else { + $message = $this->prepend_labels + ? str_replace('{field}', ucwords(str_replace('_', ' ', $field)), $message) + : str_replace('{field} ', '', $message); + } + + return $message; + } + + /** + * Convenience method to add multiple validation rules with an array + * + * @param array $rules + */ + public function rules($rules) + { + foreach ($rules as $ruleType => $params) { + if (is_array($params)) { + foreach ($params as $innerParams) { + if (!is_array($innerParams)) { + $innerParams = (array)$innerParams; + } + array_unshift($innerParams, $ruleType); + call_user_func_array(array($this, 'rule'), $innerParams); + } + } else { + $this->rule($ruleType, $params); + } + } + } + + /** + * Replace data on cloned instance + * + * @param array $data + * @param array $fields + * + * @return Validator + */ + public function withData($data, $fields = array()) + { + $clone = clone $this; + $clone->_fields = !empty($fields) ? array_intersect_key($data, array_flip($fields)) : $data; + $clone->_errors = array(); + + return $clone; + } + + /** + * Convenience method to add validation rule(s) by field + * + * @param string $field + * @param array $rules + */ + public function mapFieldRules($field, $rules) + { + $me = $this; + + array_map(function ($rule) use ($field, $me) { + //rule must be an array + $rule = (array)$rule; + + //First element is the name of the rule + $ruleName = array_shift($rule); + + //find a custom message, if any + $message = null; + if (isset($rule['message'])) { + $message = $rule['message']; + unset($rule['message']); + } + //Add the field and additional parameters to the rule + $added = call_user_func_array(array($me, 'rule'), array_merge(array($ruleName, $field), $rule)); + if (!empty($message)) { + $added->message($message); + } + }, (array)$rules); + } + + /** + * Convenience method to add validation rule(s) for multiple fields + * + * @param array $rules + */ + public function mapFieldsRules($rules) + { + $me = $this; + array_map(function ($field) use ($rules, $me) { + $me->mapFieldRules($field, $rules[$field]); + }, array_keys($rules)); + } + + private function isAssociativeArray($input) + { + //array contains at least one key that's not an can not be cast to an integer + return count(array_filter(array_keys($input), 'is_string')) > 0; + } } diff --git a/src/index.html b/src/index.html index a2c44cc..408c9de 100644 --- a/src/index.html +++ b/src/index.html @@ -1,7 +1,7 @@ - 403 Forbidden + 403 Forbidden

Directory access is forbidden.

diff --git a/src/japan/pref_code.php b/src/japan/pref_code.php index 2638b3e..531a6ac 100644 --- a/src/japan/pref_code.php +++ b/src/japan/pref_code.php @@ -9,51 +9,51 @@ * Time: 10:29 */ return array( - '01' => array('code' => '01', 'name' => 'Hokkaidō', 'kanji_name' => '北海道'), - '02' => array('code' => '02', 'name' => 'Aomori', 'kanji_name' => '青森県'), - '03' => array('code' => '03', 'name' => 'Iwate', 'kanji_name' => '岩手県'), - '04' => array('code' => '04', 'name' => 'Miyagi', 'kanji_name' => '宮城県'), - '05' => array('code' => '05', 'name' => 'Akita', 'kanji_name' => '秋田県'), - '06' => array('code' => '06', 'name' => 'Yamagata', 'kanji_name' => '山形県'), - '07' => array('code' => '07', 'name' => 'Fukushima', 'kanji_name' => '福島県'), - '08' => array('code' => '08', 'name' => 'Ibaraki', 'kanji_name' => '茨城県'), - '09' => array('code' => '09', 'name' => 'Tochigi', 'kanji_name' => '栃木県'), - '10' => array('code' => '10', 'name' => 'Gunma', 'kanji_name' => '群馬県'), - '11' => array('code' => '11', 'name' => 'Saitama', 'kanji_name' => '埼玉県'), - '12' => array('code' => '12', 'name' => 'Chiba', 'kanji_name' => '千葉県'), - '13' => array('code' => '13', 'name' => 'Tokyo', 'kanji_name' => '東京都'), - '14' => array('code' => '14', 'name' => 'Kanagawa', 'kanji_name' => '神奈川県'), - '15' => array('code' => '15', 'name' => 'Niigata', 'kanji_name' => '新潟県'), - '16' => array('code' => '16', 'name' => 'Toyama', 'kanji_name' => '富山県'), - '17' => array('code' => '17', 'name' => 'Ishikawa', 'kanji_name' => '石川県'), - '18' => array('code' => '18', 'name' => 'Fukui', 'kanji_name' => '福井県'), - '19' => array('code' => '19', 'name' => 'Yamanashi', 'kanji_name' => '山梨県'), - '20' => array('code' => '20', 'name' => 'Nagano', 'kanji_name' => '長野県'), - '21' => array('code' => '21', 'name' => 'Gifu', 'kanji_name' => '岐阜県'), - '22' => array('code' => '22', 'name' => 'Shizuoka', 'kanji_name' => '静岡県'), - '23' => array('code' => '23', 'name' => 'Aichi', 'kanji_name' => '愛知県'), - '24' => array('code' => '24', 'name' => 'Mie', 'kanji_name' => '三重県'), - '25' => array('code' => '25', 'name' => 'Shiga', 'kanji_name' => '滋賀県'), - '26' => array('code' => '26', 'name' => 'Kyoto', 'kanji_name' => '京都府'), - '27' => array('code' => '27', 'name' => 'Osaka', 'kanji_name' => '大阪府'), - '28' => array('code' => '28', 'name' => 'Hyogo', 'kanji_name' => '兵庫県'), - '29' => array('code' => '29', 'name' => 'Nara', 'kanji_name' => '奈良県'), - '30' => array('code' => '30', 'name' => 'Wakayama', 'kanji_name' => '和歌山県'), - '31' => array('code' => '31', 'name' => 'Tottori', 'kanji_name' => '鳥取県'), - '32' => array('code' => '32', 'name' => 'Shimane', 'kanji_name' => '島根県'), - '33' => array('code' => '33', 'name' => 'Okayama', 'kanji_name' => '岡山県'), - '34' => array('code' => '34', 'name' => 'Hiroshima', 'kanji_name' => '広島県'), - '35' => array('code' => '35', 'name' => 'Yamaguchi', 'kanji_name' => '山口県'), - '36' => array('code' => '36', 'name' => 'Tokushima', 'kanji_name' => '徳島県'), - '37' => array('code' => '37', 'name' => 'Kagawa', 'kanji_name' => '香川県'), - '38' => array('code' => '38', 'name' => 'Ehime', 'kanji_name' => '愛媛県'), - '39' => array('code' => '39', 'name' => 'Kochi', 'kanji_name' => '高知県'), - '40' => array('code' => '40', 'name' => 'Fukuoka', 'kanji_name' => '福岡県'), - '41' => array('code' => '41', 'name' => 'Saga', 'kanji_name' => '佐賀県'), - '42' => array('code' => '42', 'name' => 'Nagasaki', 'kanji_name' => '長崎県'), - '43' => array('code' => '43', 'name' => 'Kumamoto', 'kanji_name' => '熊本県'), - '44' => array('code' => '44', 'name' => 'Oita', 'kanji_name' => '大分県'), - '45' => array('code' => '45', 'name' => 'Miyazaki', 'kanji_name' => '宮崎県'), - '46' => array('code' => '46', 'name' => 'Kagoshima', 'kanji_name' => '鹿児島県'), - '47' => array('code' => '47', 'name' => 'Okinawa', 'kanji_name' => '沖縄県') + '01' => array('code' => '01', 'name' => 'Hokkaidō', 'kanji_name' => '北海道'), + '02' => array('code' => '02', 'name' => 'Aomori', 'kanji_name' => '青森県'), + '03' => array('code' => '03', 'name' => 'Iwate', 'kanji_name' => '岩手県'), + '04' => array('code' => '04', 'name' => 'Miyagi', 'kanji_name' => '宮城県'), + '05' => array('code' => '05', 'name' => 'Akita', 'kanji_name' => '秋田県'), + '06' => array('code' => '06', 'name' => 'Yamagata', 'kanji_name' => '山形県'), + '07' => array('code' => '07', 'name' => 'Fukushima', 'kanji_name' => '福島県'), + '08' => array('code' => '08', 'name' => 'Ibaraki', 'kanji_name' => '茨城県'), + '09' => array('code' => '09', 'name' => 'Tochigi', 'kanji_name' => '栃木県'), + '10' => array('code' => '10', 'name' => 'Gunma', 'kanji_name' => '群馬県'), + '11' => array('code' => '11', 'name' => 'Saitama', 'kanji_name' => '埼玉県'), + '12' => array('code' => '12', 'name' => 'Chiba', 'kanji_name' => '千葉県'), + '13' => array('code' => '13', 'name' => 'Tokyo', 'kanji_name' => '東京都'), + '14' => array('code' => '14', 'name' => 'Kanagawa', 'kanji_name' => '神奈川県'), + '15' => array('code' => '15', 'name' => 'Niigata', 'kanji_name' => '新潟県'), + '16' => array('code' => '16', 'name' => 'Toyama', 'kanji_name' => '富山県'), + '17' => array('code' => '17', 'name' => 'Ishikawa', 'kanji_name' => '石川県'), + '18' => array('code' => '18', 'name' => 'Fukui', 'kanji_name' => '福井県'), + '19' => array('code' => '19', 'name' => 'Yamanashi', 'kanji_name' => '山梨県'), + '20' => array('code' => '20', 'name' => 'Nagano', 'kanji_name' => '長野県'), + '21' => array('code' => '21', 'name' => 'Gifu', 'kanji_name' => '岐阜県'), + '22' => array('code' => '22', 'name' => 'Shizuoka', 'kanji_name' => '静岡県'), + '23' => array('code' => '23', 'name' => 'Aichi', 'kanji_name' => '愛知県'), + '24' => array('code' => '24', 'name' => 'Mie', 'kanji_name' => '三重県'), + '25' => array('code' => '25', 'name' => 'Shiga', 'kanji_name' => '滋賀県'), + '26' => array('code' => '26', 'name' => 'Kyoto', 'kanji_name' => '京都府'), + '27' => array('code' => '27', 'name' => 'Osaka', 'kanji_name' => '大阪府'), + '28' => array('code' => '28', 'name' => 'Hyogo', 'kanji_name' => '兵庫県'), + '29' => array('code' => '29', 'name' => 'Nara', 'kanji_name' => '奈良県'), + '30' => array('code' => '30', 'name' => 'Wakayama', 'kanji_name' => '和歌山県'), + '31' => array('code' => '31', 'name' => 'Tottori', 'kanji_name' => '鳥取県'), + '32' => array('code' => '32', 'name' => 'Shimane', 'kanji_name' => '島根県'), + '33' => array('code' => '33', 'name' => 'Okayama', 'kanji_name' => '岡山県'), + '34' => array('code' => '34', 'name' => 'Hiroshima', 'kanji_name' => '広島県'), + '35' => array('code' => '35', 'name' => 'Yamaguchi', 'kanji_name' => '山口県'), + '36' => array('code' => '36', 'name' => 'Tokushima', 'kanji_name' => '徳島県'), + '37' => array('code' => '37', 'name' => 'Kagawa', 'kanji_name' => '香川県'), + '38' => array('code' => '38', 'name' => 'Ehime', 'kanji_name' => '愛媛県'), + '39' => array('code' => '39', 'name' => 'Kochi', 'kanji_name' => '高知県'), + '40' => array('code' => '40', 'name' => 'Fukuoka', 'kanji_name' => '福岡県'), + '41' => array('code' => '41', 'name' => 'Saga', 'kanji_name' => '佐賀県'), + '42' => array('code' => '42', 'name' => 'Nagasaki', 'kanji_name' => '長崎県'), + '43' => array('code' => '43', 'name' => 'Kumamoto', 'kanji_name' => '熊本県'), + '44' => array('code' => '44', 'name' => 'Oita', 'kanji_name' => '大分県'), + '45' => array('code' => '45', 'name' => 'Miyazaki', 'kanji_name' => '宮崎県'), + '46' => array('code' => '46', 'name' => 'Kagoshima', 'kanji_name' => '鹿児島県'), + '47' => array('code' => '47', 'name' => 'Okinawa', 'kanji_name' => '沖縄県') ); diff --git a/src/validator/lang/ar.php b/src/validator/lang/ar.php index 1f294c3..664d609 100644 --- a/src/validator/lang/ar.php +++ b/src/validator/lang/ar.php @@ -1,28 +1,29 @@ "مطلوب", - 'equals' => "يجب أن يكون مساوي لي '%s'", - 'different' => "يجب ان يكون غير '%s'", - 'accepted' => "يجب ان يكون نعم", - 'numeric' => "يجب ان يكون رقم", - 'integer' => "يجب ان يكون رقم (0-9)", - 'length' => "يجب ان يكون أطول من %d", - 'min' => "يجب ان يكون اعلي من %s", - 'max' => "يجب ان يكون اقل من %s", - 'in' => "الُمدخل يغير صحيح", + 'required' => "مطلوب", + 'equals' => "يجب أن يكون مساوي لي '%s'", + 'different' => "يجب ان يكون غير '%s'", + 'accepted' => "يجب ان يكون نعم", + 'numeric' => "يجب ان يكون رقم", + 'integer' => "يجب ان يكون رقم (0-9)", + 'length' => "يجب ان يكون أطول من %d", + 'min' => "يجب ان يكون اعلي من %s", + 'max' => "يجب ان يكون اقل من %s", + 'in' => "الُمدخل يغير صحيح", 'listContains' => "الُمدخل يغير صحيح", - 'notIn' => "الُمدخل يغير صحيح", - 'ip' => "رقم الإتصال غير صحيح", - 'email' => "البريد الألكتروني غير صحيح", - 'url' => "الرابط غير صحيح", - 'urlActive' => "يجب أن يكون نطاق فعال", - 'alpha' => "يجب أن يحتوي فقط علي a-z", - 'alphaNum' => "يجب ان يحتوي فقط a-z او ارقام 0-9", - 'slug' => "يجب ان يحتوي فقط علي a-z, و ارقام 0-9, شرطات و خط سفلي", - 'regex' => "خطا بالصيغة", - 'date' => "خطا بالتاريخ", - 'dateFormat' => "يجب ان يكون تاريخ بهذه الصيغة '%s'", - 'dateBefore' => "التاريخ يجب ان يكون قبل '%s'", - 'dateAfter' => "التاريخ يجب ان يكون بعد '%s'", - 'contains' => "يجب ان يحتوي %s" + 'notIn' => "الُمدخل يغير صحيح", + 'ip' => "رقم الإتصال غير صحيح", + 'email' => "البريد الألكتروني غير صحيح", + 'url' => "الرابط غير صحيح", + 'urlActive' => "يجب أن يكون نطاق فعال", + 'alpha' => "يجب أن يحتوي فقط علي a-z", + 'alphaNum' => "يجب ان يحتوي فقط a-z او ارقام 0-9", + 'slug' => "يجب ان يحتوي فقط علي a-z, و ارقام 0-9, شرطات و خط سفلي", + 'regex' => "خطا بالصيغة", + 'date' => "خطا بالتاريخ", + 'dateFormat' => "يجب ان يكون تاريخ بهذه الصيغة '%s'", + 'dateBefore' => "التاريخ يجب ان يكون قبل '%s'", + 'dateAfter' => "التاريخ يجب ان يكون بعد '%s'", + 'contains' => "يجب ان يحتوي %s" ); diff --git a/src/validator/lang/az.php b/src/validator/lang/az.php index 231fa82..6f434c1 100644 --- a/src/validator/lang/az.php +++ b/src/validator/lang/az.php @@ -1,34 +1,35 @@ "mütləqdir", - 'equals' => "'%s' olmalıdır", - 'different' => "'%s'-dən fərqli olmalıdır", - 'accepted' => "Qeyd dilməlidir", - 'numeric' => "rəqəm olmalıdır", - 'integer' => "tam ədəd olmalıdır", - 'length' => "%d qədər uzunluğu olmalıdır", - 'min' => "minimum %s qədər olmalıdır", - 'max' => "maksimum %s qədər olmalıdır", - 'listContains' => "yalnış dəyər ehtiva edir", - 'in' => "yalnış dəyər ehtiva edir", - 'notIn' => "yalnış dəyər ehtiva edir", - 'ip' => "düzgün IP ünvanı deyil", - 'email' => "düzgün email ünvanı deyil", - 'url' => "URL deyil", - 'urlActive' => "aktiv domain olmalıdır", - 'alpha' => "ancaq latın hərfləri ehtiva etməlidir", - 'alphaNum' => "ancaq latın hərfləri və(və ya) rəqəmlər ehtiva etməlidir", - 'slug' => "ancaq latın hərfləri,rəqəmlər,tire və altdan xət ehtiva etməlidir", - 'regex' => "etiabrsız sinvollar ehtiva edir", - 'date' => "tarix deyil", - 'dateFormat' => "tarix formatı bu cür olmalıdır: %s", - 'dateBefore' => "tarix %s -dən əvvəl olmamalıdır", - 'dateAfter' => "tarix %s -dən sonra olmamalıdır", - 'contains' => "%s ehtiva etməlidir", - 'boolean' => "boolen olmalıdır", + 'required' => "mütləqdir", + 'equals' => "'%s' olmalıdır", + 'different' => "'%s'-dən fərqli olmalıdır", + 'accepted' => "Qeyd dilməlidir", + 'numeric' => "rəqəm olmalıdır", + 'integer' => "tam ədəd olmalıdır", + 'length' => "%d qədər uzunluğu olmalıdır", + 'min' => "minimum %s qədər olmalıdır", + 'max' => "maksimum %s qədər olmalıdır", + 'listContains' => "yalnış dəyər ehtiva edir", + 'in' => "yalnış dəyər ehtiva edir", + 'notIn' => "yalnış dəyər ehtiva edir", + 'ip' => "düzgün IP ünvanı deyil", + 'email' => "düzgün email ünvanı deyil", + 'url' => "URL deyil", + 'urlActive' => "aktiv domain olmalıdır", + 'alpha' => "ancaq latın hərfləri ehtiva etməlidir", + 'alphaNum' => "ancaq latın hərfləri və(və ya) rəqəmlər ehtiva etməlidir", + 'slug' => "ancaq latın hərfləri,rəqəmlər,tire və altdan xət ehtiva etməlidir", + 'regex' => "etiabrsız sinvollar ehtiva edir", + 'date' => "tarix deyil", + 'dateFormat' => "tarix formatı bu cür olmalıdır: %s", + 'dateBefore' => "tarix %s -dən əvvəl olmamalıdır", + 'dateAfter' => "tarix %s -dən sonra olmamalıdır", + 'contains' => "%s ehtiva etməlidir", + 'boolean' => "boolen olmalıdır", 'lengthBetween' => "%d - %d sinvolları arası ehtiva etməlidir", - 'creditCard' => "kredir kart nömrəsi olmalıdır", - "lengthMin" => "%d -dən çox sinvol olmalıdır", - "lengthMax" => "%d -dən az sinvol olmalıdır", - "instanceOf" => "'%s' əvəzinə olmalıdır" + 'creditCard' => "kredir kart nömrəsi olmalıdır", + "lengthMin" => "%d -dən çox sinvol olmalıdır", + "lengthMax" => "%d -dən az sinvol olmalıdır", + "instanceOf" => "'%s' əvəzinə olmalıdır" ); diff --git a/src/validator/lang/bg.php b/src/validator/lang/bg.php index 2166b11..400544e 100644 --- a/src/validator/lang/bg.php +++ b/src/validator/lang/bg.php @@ -1,35 +1,35 @@ "е задължително", - 'equals' => "трябва да бъде същото като '%s'", - 'different' => "трябва да бъде различно от '%s'", - 'accepted' => "трабва да бъде прието", - 'numeric' => "трябва да бъде число", - 'integer' => "трябва да бъде цифра (0-9)", - 'length' => "трябва да бъде %d символа дълго", - 'min' => "трябвя да бъде поне %s", - 'max' => "трябва да бъде не повече от %s", - 'listContains' => "съдържа невалидна стойност", - 'in' => "съдържа невалидна стойност", - 'notIn' => "съдържа невалидна стойност", - 'ip' => "е невалиден IP адрес", - 'email' => "е невалиден имейл адрес", - 'url' => "е невалиден URL адрес", - 'urlActive' => "трябва да бъде активен домейн", - 'alpha' => "трябва да съдържа само букви a-z", - 'alphaNum' => "трябва да съдържа само букви a-z и/или цифри 0-9", - 'slug' => "трябва да съдържа само букви a-z, цифри 0-9, тирета и долни черти", - 'regex' => "съдържа невалидни символи", - 'date' => "е невалидна дата", - 'dateFormat' => "трябва да бъде дата с формат '%s'", - 'dateBefore' => "трябва да бъде дата преди '%s'", - 'dateAfter' => "трябва да бъде дата след '%s'", - 'contains' => "трябв да съдържа %s", - 'boolean' => "трябва да бъде истина или лъжа", + 'required' => "е задължително", + 'equals' => "трябва да бъде същото като '%s'", + 'different' => "трябва да бъде различно от '%s'", + 'accepted' => "трабва да бъде прието", + 'numeric' => "трябва да бъде число", + 'integer' => "трябва да бъде цифра (0-9)", + 'length' => "трябва да бъде %d символа дълго", + 'min' => "трябвя да бъде поне %s", + 'max' => "трябва да бъде не повече от %s", + 'listContains' => "съдържа невалидна стойност", + 'in' => "съдържа невалидна стойност", + 'notIn' => "съдържа невалидна стойност", + 'ip' => "е невалиден IP адрес", + 'email' => "е невалиден имейл адрес", + 'url' => "е невалиден URL адрес", + 'urlActive' => "трябва да бъде активен домейн", + 'alpha' => "трябва да съдържа само букви a-z", + 'alphaNum' => "трябва да съдържа само букви a-z и/или цифри 0-9", + 'slug' => "трябва да съдържа само букви a-z, цифри 0-9, тирета и долни черти", + 'regex' => "съдържа невалидни символи", + 'date' => "е невалидна дата", + 'dateFormat' => "трябва да бъде дата с формат '%s'", + 'dateBefore' => "трябва да бъде дата преди '%s'", + 'dateAfter' => "трябва да бъде дата след '%s'", + 'contains' => "трябв да съдържа %s", + 'boolean' => "трябва да бъде истина или лъжа", 'lengthBetween' => "трябва да бъде между %d и %d символа", - 'creditCard' => "трябва да бъде валиден номер на кредитна карта", - 'lengthMin' => "трябва да бъде поне %d символа дълго", - 'lengthMax' => "не трябва да надвишава %d символа", - 'instanceOf' => "трябва да бъде инстанция от '%s'" + 'creditCard' => "трябва да бъде валиден номер на кредитна карта", + 'lengthMin' => "трябва да бъде поне %d символа дълго", + 'lengthMax' => "не трябва да надвишава %d символа", + 'instanceOf' => "трябва да бъде инстанция от '%s'" ); diff --git a/src/validator/lang/de.php b/src/validator/lang/de.php index 4e7ae07..02eeb27 100644 --- a/src/validator/lang/de.php +++ b/src/validator/lang/de.php @@ -1,34 +1,34 @@ "ist erforderlich", - 'equals' => "muss identisch mit '%s' sein", - 'different' => "muss sich von '%s' unterscheiden", - 'accepted' => "muss markiert sein", - 'numeric' => "muss eine Zahl sein", - 'integer' => "muss eine ganze Zahl sein", - 'length' => "kann nicht länger als %d sein", - 'min' => "muss größer als %s sein", - 'max' => "muss kleiner als %s sein", - 'listContains' => "enthält einen ungültigen Wert", - 'in' => "enthält einen ungültigen Wert", - 'notIn' => "enthält einen ungültigen Wert", - 'ip' => "enthält keine gültige IP-Addresse", - 'email' => "enthält keine gültige E-Mail-Adresse", - 'url' => "enthält keine gültige URL", - 'urlActive' => "muss eine aktive Domain sein", - 'alpha' => "darf nur Buchstaben enthalten", - 'alphaNum' => "darf nur Buchstaben und Ganzzahlen enthalten", - 'slug' => "darf nur Buchstaben, Ganzzahlen, Schrägstriche und Grundstriche enthalten", - 'regex' => "enthält ungültige Zeichen", - 'date' => "enthält kein gültiges Datum", - 'dateFormat' => "benötigt ein Datum im Format '%s'", - 'dateBefore' => "benötigt ein Datum, das vor dem '%s' liegt", - 'dateAfter' => "benötigt ein Datum, das nach dem '%s' liegt", - 'contains' => "muss %s beinhalten", - 'boolean' => "muss ein Wahrheitswert sein", + 'required' => "ist erforderlich", + 'equals' => "muss identisch mit '%s' sein", + 'different' => "muss sich von '%s' unterscheiden", + 'accepted' => "muss markiert sein", + 'numeric' => "muss eine Zahl sein", + 'integer' => "muss eine ganze Zahl sein", + 'length' => "kann nicht länger als %d sein", + 'min' => "muss größer als %s sein", + 'max' => "muss kleiner als %s sein", + 'listContains' => "enthält einen ungültigen Wert", + 'in' => "enthält einen ungültigen Wert", + 'notIn' => "enthält einen ungültigen Wert", + 'ip' => "enthält keine gültige IP-Addresse", + 'email' => "enthält keine gültige E-Mail-Adresse", + 'url' => "enthält keine gültige URL", + 'urlActive' => "muss eine aktive Domain sein", + 'alpha' => "darf nur Buchstaben enthalten", + 'alphaNum' => "darf nur Buchstaben und Ganzzahlen enthalten", + 'slug' => "darf nur Buchstaben, Ganzzahlen, Schrägstriche und Grundstriche enthalten", + 'regex' => "enthält ungültige Zeichen", + 'date' => "enthält kein gültiges Datum", + 'dateFormat' => "benötigt ein Datum im Format '%s'", + 'dateBefore' => "benötigt ein Datum, das vor dem '%s' liegt", + 'dateAfter' => "benötigt ein Datum, das nach dem '%s' liegt", + 'contains' => "muss %s beinhalten", + 'boolean' => "muss ein Wahrheitswert sein", 'lengthBetween' => "benötigt zwischen %d und %d Zeichen", - 'creditCard' => "muss eine gültige Kreditkartennummer sein", - "lengthMin" => "muss mindestens %d Zeichen enthalten", - "lengthMax" => "kann nicht mehr als %d Zeichen enthalten" + 'creditCard' => "muss eine gültige Kreditkartennummer sein", + "lengthMin" => "muss mindestens %d Zeichen enthalten", + "lengthMax" => "kann nicht mehr als %d Zeichen enthalten" ); diff --git a/src/validator/lang/el.php b/src/validator/lang/el.php index ae35aaf..75371c4 100644 --- a/src/validator/lang/el.php +++ b/src/validator/lang/el.php @@ -1,35 +1,35 @@ "είναι απαραίτητο", - 'equals' => "πρέπει να είναι ίδιο με '%s'", - 'different' => "πρέπει να διαφέρει από '%s'", - 'accepted' => "πρέπει να έχει αποδεχτεί", - 'numeric' => "πρέπει να είναι αριθμός", - 'integer' => "πρέπει να είναι ακέραιος αριθμός", - 'length' => "πρέπει να είναι μεγαλύτερο από %d", - 'min' => "πρέπει να είναι τουλάχιστον %s", - 'max' => "δεν πρέπει να είναι περισσότερο από %s", - 'listContains' => "περιέχει μη έγκυρη τιμή", - 'in' => "περιέχει μη έγκυρη τιμή", - 'notIn' => "περιέχει μη έγκυρη τιμή", - 'ip' => "δεν είναι έγκυρη διεύθυνση IP", - 'email' => "δεν είναι έγκυρη διεύθυνση email", - 'url' => "δεν είναι URL", - 'urlActive' => "πρέπει να είναι ενεργό domain", - 'alpha' => "πρέπει να περιέχει μόνο χαρακτήρες", - 'alphaNum' => "πρέπει να περιέχει μόνο χαρακτήρες και/ή αριθμούς", - 'slug' => "πρέπει να περιέχει μόνο χαρακτήρες, αριθμούς, παύλες και κάτω παύλες", - 'regex' => "περιέχει μη έγκυρους χαρακτήρες", - 'date' => "δεν είναι έγκυρη ημερομηνία", - 'dateFormat' => "πρέπει να είναι ημερομηνία της μορφής '%s'", - 'dateBefore' => "πρέπει να είναι ημερομηνία πριν από '%s'", - 'dateAfter' => "πρέπει να είναι ημερομηνία μετά από '%s'", - 'contains' => "πρέπει να περιέχει %s", - 'boolean' => "πρέπει να είναι boolean", + 'required' => "είναι απαραίτητο", + 'equals' => "πρέπει να είναι ίδιο με '%s'", + 'different' => "πρέπει να διαφέρει από '%s'", + 'accepted' => "πρέπει να έχει αποδεχτεί", + 'numeric' => "πρέπει να είναι αριθμός", + 'integer' => "πρέπει να είναι ακέραιος αριθμός", + 'length' => "πρέπει να είναι μεγαλύτερο από %d", + 'min' => "πρέπει να είναι τουλάχιστον %s", + 'max' => "δεν πρέπει να είναι περισσότερο από %s", + 'listContains' => "περιέχει μη έγκυρη τιμή", + 'in' => "περιέχει μη έγκυρη τιμή", + 'notIn' => "περιέχει μη έγκυρη τιμή", + 'ip' => "δεν είναι έγκυρη διεύθυνση IP", + 'email' => "δεν είναι έγκυρη διεύθυνση email", + 'url' => "δεν είναι URL", + 'urlActive' => "πρέπει να είναι ενεργό domain", + 'alpha' => "πρέπει να περιέχει μόνο χαρακτήρες", + 'alphaNum' => "πρέπει να περιέχει μόνο χαρακτήρες και/ή αριθμούς", + 'slug' => "πρέπει να περιέχει μόνο χαρακτήρες, αριθμούς, παύλες και κάτω παύλες", + 'regex' => "περιέχει μη έγκυρους χαρακτήρες", + 'date' => "δεν είναι έγκυρη ημερομηνία", + 'dateFormat' => "πρέπει να είναι ημερομηνία της μορφής '%s'", + 'dateBefore' => "πρέπει να είναι ημερομηνία πριν από '%s'", + 'dateAfter' => "πρέπει να είναι ημερομηνία μετά από '%s'", + 'contains' => "πρέπει να περιέχει %s", + 'boolean' => "πρέπει να είναι boolean", 'lengthBetween' => "πρέπει να είναι μεταξύ %d και %d χαρακτήρων", - 'creditCard' => "πρέπει να είναι ένα έγκυρο νούμερο πιστωτικής κάρτας", - "lengthMin" => "πρέπει να περιέχει περισσότερους από %d χαρακτήρες", - "lengthMax" => "πρέπει να περιέχει λιγότερους από %d χαρακτήρες", - "instanceOf" => "πρέπει να είναι αντικείμενο της '%s'" + 'creditCard' => "πρέπει να είναι ένα έγκυρο νούμερο πιστωτικής κάρτας", + "lengthMin" => "πρέπει να περιέχει περισσότερους από %d χαρακτήρες", + "lengthMax" => "πρέπει να περιέχει λιγότερους από %d χαρακτήρες", + "instanceOf" => "πρέπει να είναι αντικείμενο της '%s'" ); diff --git a/src/validator/lang/en.php b/src/validator/lang/en.php index 8e66cb5..af0d3b7 100644 --- a/src/validator/lang/en.php +++ b/src/validator/lang/en.php @@ -1,42 +1,42 @@ "is required", - 'equals' => "must be the same as '%s'", - 'different' => "must be different than '%s'", - 'accepted' => "must be accepted", - 'numeric' => "must be numeric", - 'integer' => "must be an integer", - 'length' => "must be %d characters long", - 'min' => "must be at least %s", - 'max' => "must be no more than %s", - 'listContains' => "contains invalid value", - 'in' => "contains invalid value", - 'notIn' => "contains invalid value", - 'ip' => "is not a valid IP address", - 'ipv4' => "is not a valid IPv4 address", - 'ipv6' => "is not a valid IPv6 address", - 'email' => "is not a valid email address", - 'url' => "is not a valid URL", - 'urlActive' => "must be an active domain", - 'alpha' => "must contain only letters a-z", - 'alphaNum' => "must contain only letters a-z and/or numbers 0-9", - 'slug' => "must contain only letters a-z, numbers 0-9, dashes and underscores", - 'regex' => "contains invalid characters", - 'date' => "is not a valid date", - 'dateFormat' => "must be date with format '%s'", - 'dateBefore' => "must be date before '%s'", - 'dateAfter' => "must be date after '%s'", - 'contains' => "must contain %s", - 'boolean' => "must be a boolean", - 'lengthBetween' => "must be between %d and %d characters", - 'creditCard' => "must be a valid credit card number", - 'lengthMin' => "must be at least %d characters long", - 'lengthMax' => "must not exceed %d characters", - 'instanceOf' => "must be an instance of '%s'", + 'required' => "is required", + 'equals' => "must be the same as '%s'", + 'different' => "must be different than '%s'", + 'accepted' => "must be accepted", + 'numeric' => "must be numeric", + 'integer' => "must be an integer", + 'length' => "must be %d characters long", + 'min' => "must be at least %s", + 'max' => "must be no more than %s", + 'listContains' => "contains invalid value", + 'in' => "contains invalid value", + 'notIn' => "contains invalid value", + 'ip' => "is not a valid IP address", + 'ipv4' => "is not a valid IPv4 address", + 'ipv6' => "is not a valid IPv6 address", + 'email' => "is not a valid email address", + 'url' => "is not a valid URL", + 'urlActive' => "must be an active domain", + 'alpha' => "must contain only letters a-z", + 'alphaNum' => "must contain only letters a-z and/or numbers 0-9", + 'slug' => "must contain only letters a-z, numbers 0-9, dashes and underscores", + 'regex' => "contains invalid characters", + 'date' => "is not a valid date", + 'dateFormat' => "must be date with format '%s'", + 'dateBefore' => "must be date before '%s'", + 'dateAfter' => "must be date after '%s'", + 'contains' => "must contain %s", + 'boolean' => "must be a boolean", + 'lengthBetween' => "must be between %d and %d characters", + 'creditCard' => "must be a valid credit card number", + 'lengthMin' => "must be at least %d characters long", + 'lengthMax' => "must not exceed %d characters", + 'instanceOf' => "must be an instance of '%s'", 'containsUnique' => "must contain unique elements only", - 'requiredWith' => "is required", - 'requiredWithout'=> "is required", - 'subset' => "contains an item that is not in the list", - 'arrayHasKeys' => "does not contain all required keys", + 'requiredWith' => "is required", + 'requiredWithout' => "is required", + 'subset' => "contains an item that is not in the list", + 'arrayHasKeys' => "does not contain all required keys", ); diff --git a/src/validator/lang/es.php b/src/validator/lang/es.php index 1f3bf8b..b3ab9a8 100644 --- a/src/validator/lang/es.php +++ b/src/validator/lang/es.php @@ -1,37 +1,37 @@ "es obligatorio", - 'equals' => "debe ser igual a '%s'", - 'different' => "debe ser diferente a '%s'", - 'accepted' => "debe ser aceptado", - 'numeric' => "debe ser numérico", - 'integer' => "debe ser un entero", - 'length' => "debe ser mas largo de %d", - 'min' => "debe ser mayor de %s", - 'max' => "debe ser menor de %s", - 'in' => "contiene un valor inválido", - 'notIn' => "contiene un valor inválido", - 'ip' => "no es una dirección IP", - 'email' => "no es un correo electrónico válido", - 'url' => "no es una URL", - 'urlActive' => "debe ser un dominio activo", - 'alpha' => "debe contener solo letras a-z", - 'alphaNum' => "debe contener solo letras a-z o números 0-9", - 'slug' => "debe contener solo letras a-z, números 0-9, barras y guiones bajos", - 'regex' => "contiene caracteres inválidos", - 'date' => "no es una fecha válida", - 'dateFormat' => "debe ser una fecha con formato '%s'", - 'dateBefore' => "debe ser una fecha antes de '%s'", - 'dateAfter' => "debe ser una fecha después de '%s'", - 'contains' => "debe contener %s", - 'boolean' => "debe ser booleano", - 'lengthBetween' => "debe tener entre %d y %d caracteres", - 'creditCard' => "debe ser un numero de tarjeta de crédito válido", - "lengthMin" => "debe tener al menos %d caracteres", - "lengthMax" => "debe tener menos de %d caracteres", - "instanceOf" => "debe ser una instancia de '%s'", + 'required' => "es obligatorio", + 'equals' => "debe ser igual a '%s'", + 'different' => "debe ser diferente a '%s'", + 'accepted' => "debe ser aceptado", + 'numeric' => "debe ser numérico", + 'integer' => "debe ser un entero", + 'length' => "debe ser mas largo de %d", + 'min' => "debe ser mayor de %s", + 'max' => "debe ser menor de %s", + 'in' => "contiene un valor inválido", + 'notIn' => "contiene un valor inválido", + 'ip' => "no es una dirección IP", + 'email' => "no es un correo electrónico válido", + 'url' => "no es una URL", + 'urlActive' => "debe ser un dominio activo", + 'alpha' => "debe contener solo letras a-z", + 'alphaNum' => "debe contener solo letras a-z o números 0-9", + 'slug' => "debe contener solo letras a-z, números 0-9, barras y guiones bajos", + 'regex' => "contiene caracteres inválidos", + 'date' => "no es una fecha válida", + 'dateFormat' => "debe ser una fecha con formato '%s'", + 'dateBefore' => "debe ser una fecha antes de '%s'", + 'dateAfter' => "debe ser una fecha después de '%s'", + 'contains' => "debe contener %s", + 'boolean' => "debe ser booleano", + 'lengthBetween' => "debe tener entre %d y %d caracteres", + 'creditCard' => "debe ser un numero de tarjeta de crédito válido", + "lengthMin" => "debe tener al menos %d caracteres", + "lengthMax" => "debe tener menos de %d caracteres", + "instanceOf" => "debe ser una instancia de '%s'", 'containsUnique' => "debe contener solo valores únicos", - 'subset' => "contiene un elemento que no está en la lista", - 'arrayHasKeys' => "no contiene todas las claves requeridas" + 'subset' => "contiene un elemento que no está en la lista", + 'arrayHasKeys' => "no contiene todas las claves requeridas" ); diff --git a/src/validator/lang/fa.php b/src/validator/lang/fa.php index 0521a6c..a81d5a2 100644 --- a/src/validator/lang/fa.php +++ b/src/validator/lang/fa.php @@ -1,42 +1,42 @@ "الزامی است", - 'equals' => " باید برابر باشد با '%s'", - 'different' => "باید متفاوت باشد از '%s'", - 'accepted' => "باید پذیرفته شده باشد", - 'numeric' => "باید مقدار عددی باشد", - 'integer' => "باید عددی طبیعی باشد", - 'length' => "طول باید %d باشد", - 'min' => "حداقل باید %s کاراکتر باشد", - 'max' => "نباید بیشتر از %s کارکتر باشد", - 'listContains' => "حاوی مقدار نامعتبر", - 'in' => "حاوی مقدار نامعتبر", - 'notIn' => "حاوی مقدار نامعتبر", - 'ip' => " آدرس معتبر نیست IP", - 'ipv4' => "آدرس معتبر نیست IPv4", - 'ipv6' => "آدرس معتبر نیست IPv6", - 'email' => "آدرس ایمیل معتبر نیست", - 'url' => "معتبر نیست URL", - 'urlActive' => "دامنه باید فعال باشد", - 'alpha' => "باید حاوی حروف a-z باشد", - 'alphaNum' => "باید حاوی حروف a-z و/یا اعداد 0-9 باشد", - 'slug' => "باید حاوی حروف a-z, اعداد 0-9, دش و آندراسکور باشد", - 'regex' => "حاوی کارکترهای نامعتبر", - 'date' => "تاریخ معتبر نیست", - 'dateFormat' => "فرمت تاریخ باید به این شکل '%s' باشد", - 'dateBefore' => "تاریخ باید قبل از '%s' باشد", - 'dateAfter' => "تاریخ باید بعد از '%s' باشد", - 'contains' => "باید حاوی %s باشد", - 'boolean' => "مقدار باید بولین باشد", - 'lengthBetween' => "طول باید بین %d و %d کاراکتر باشد", - 'creditCard' => "شماره کارت اعتباری معتبر نیست", - 'lengthMin' => "طول باید حداقل %d کاراکتر باشد", - 'lengthMax' => "طول نباید بیشتر از %d کاراکتر باشد", - 'instanceOf' => "باید آبجکتی از نوع '%s' باشد", + 'required' => "الزامی است", + 'equals' => " باید برابر باشد با '%s'", + 'different' => "باید متفاوت باشد از '%s'", + 'accepted' => "باید پذیرفته شده باشد", + 'numeric' => "باید مقدار عددی باشد", + 'integer' => "باید عددی طبیعی باشد", + 'length' => "طول باید %d باشد", + 'min' => "حداقل باید %s کاراکتر باشد", + 'max' => "نباید بیشتر از %s کارکتر باشد", + 'listContains' => "حاوی مقدار نامعتبر", + 'in' => "حاوی مقدار نامعتبر", + 'notIn' => "حاوی مقدار نامعتبر", + 'ip' => " آدرس معتبر نیست IP", + 'ipv4' => "آدرس معتبر نیست IPv4", + 'ipv6' => "آدرس معتبر نیست IPv6", + 'email' => "آدرس ایمیل معتبر نیست", + 'url' => "معتبر نیست URL", + 'urlActive' => "دامنه باید فعال باشد", + 'alpha' => "باید حاوی حروف a-z باشد", + 'alphaNum' => "باید حاوی حروف a-z و/یا اعداد 0-9 باشد", + 'slug' => "باید حاوی حروف a-z, اعداد 0-9, دش و آندراسکور باشد", + 'regex' => "حاوی کارکترهای نامعتبر", + 'date' => "تاریخ معتبر نیست", + 'dateFormat' => "فرمت تاریخ باید به این شکل '%s' باشد", + 'dateBefore' => "تاریخ باید قبل از '%s' باشد", + 'dateAfter' => "تاریخ باید بعد از '%s' باشد", + 'contains' => "باید حاوی %s باشد", + 'boolean' => "مقدار باید بولین باشد", + 'lengthBetween' => "طول باید بین %d و %d کاراکتر باشد", + 'creditCard' => "شماره کارت اعتباری معتبر نیست", + 'lengthMin' => "طول باید حداقل %d کاراکتر باشد", + 'lengthMax' => "طول نباید بیشتر از %d کاراکتر باشد", + 'instanceOf' => "باید آبجکتی از نوع '%s' باشد", 'containsUnique' => "باید حاوی المان ها یونیک باشد", - 'requiredWith' => "الزامی است", - 'requiredWithout'=> "الزامی است", - 'subset' => "حاوی آیتمی است که در لیست موجود نیست", - 'arrayHasKeys' => "همه کلیدهای الزامی را ندارد", + 'requiredWith' => "الزامی است", + 'requiredWithout' => "الزامی است", + 'subset' => "حاوی آیتمی است که در لیست موجود نیست", + 'arrayHasKeys' => "همه کلیدهای الزامی را ندارد", ); diff --git a/src/validator/lang/fi.php b/src/validator/lang/fi.php index 4754e08..544f6fa 100644 --- a/src/validator/lang/fi.php +++ b/src/validator/lang/fi.php @@ -1,34 +1,35 @@ "vaaditaan", - 'equals' => "ei ole sama kuin '%s'", - 'different' => "on sama kuin '%s'", - 'accepted' => "ei ole hyväksytty", - 'numeric' => "ei ole numeerinen", - 'integer' => "ei ole kokonaisluku", - 'length' => "on lyhyempi kuin %d", - 'min' => "ei ole vähintään %s", - 'max' => "ei ole enintään %s", - 'listContains' => "sisältää virheellisen arvon", - 'in' => "sisältää virheellisen arvon", - 'notIn' => "sisältää virheellisen arvon", - 'ip' => "ei ole oikeanmuotoinen IP-osoite", - 'email' => "ei ole oikeanmuotoinen sähköpostiosoite", - 'url' => "ei ole URL", - 'urlActive' => "ei ole aktiivinen verkkotunnus", - 'alpha' => "sisältää muita merkkejä kuin a-z", - 'alphaNum' => "sisältää muita merkkejä kuin a-z ja 0-9", - 'slug' => "sisältää muita merkkejä kuin a-z, 0-9, - ja _", - 'regex' => "sisältää virheellisiä merkkejä", - 'date' => "ei ole oikeanmuotoinen päivämäärä", - 'dateFormat' => "ei ole päivämäärä muotoa '%s'", - 'dateBefore' => "ei ole päivämäärä ennen '%s'", - 'dateAfter' => "ei ole päivämäärä '%s' jälkeen", - 'contains' => "ei sisällä merkkijonoa %s", - 'boolean' => "ei ole totuusarvo", + 'required' => "vaaditaan", + 'equals' => "ei ole sama kuin '%s'", + 'different' => "on sama kuin '%s'", + 'accepted' => "ei ole hyväksytty", + 'numeric' => "ei ole numeerinen", + 'integer' => "ei ole kokonaisluku", + 'length' => "on lyhyempi kuin %d", + 'min' => "ei ole vähintään %s", + 'max' => "ei ole enintään %s", + 'listContains' => "sisältää virheellisen arvon", + 'in' => "sisältää virheellisen arvon", + 'notIn' => "sisältää virheellisen arvon", + 'ip' => "ei ole oikeanmuotoinen IP-osoite", + 'email' => "ei ole oikeanmuotoinen sähköpostiosoite", + 'url' => "ei ole URL", + 'urlActive' => "ei ole aktiivinen verkkotunnus", + 'alpha' => "sisältää muita merkkejä kuin a-z", + 'alphaNum' => "sisältää muita merkkejä kuin a-z ja 0-9", + 'slug' => "sisältää muita merkkejä kuin a-z, 0-9, - ja _", + 'regex' => "sisältää virheellisiä merkkejä", + 'date' => "ei ole oikeanmuotoinen päivämäärä", + 'dateFormat' => "ei ole päivämäärä muotoa '%s'", + 'dateBefore' => "ei ole päivämäärä ennen '%s'", + 'dateAfter' => "ei ole päivämäärä '%s' jälkeen", + 'contains' => "ei sisällä merkkijonoa %s", + 'boolean' => "ei ole totuusarvo", 'lengthBetween' => "ei ole %d-%d merkkiä pitkä", - 'creditCard' => "ei ole pätevä luottokortin numero", - "lengthMin" => "ei ole vähintään %d merkkiä pitkä", - "lengthMax" => "ei ole enintään %d merkkiä pitkä", - "instanceOf" => "ei ole luokan '%s' ilmentymä" + 'creditCard' => "ei ole pätevä luottokortin numero", + "lengthMin" => "ei ole vähintään %d merkkiä pitkä", + "lengthMax" => "ei ole enintään %d merkkiä pitkä", + "instanceOf" => "ei ole luokan '%s' ilmentymä" ); diff --git a/src/validator/lang/fr.php b/src/validator/lang/fr.php index 124cdac..f579495 100644 --- a/src/validator/lang/fr.php +++ b/src/validator/lang/fr.php @@ -1,40 +1,40 @@ "est obligatoire", - 'equals' => "doit être identique à '%s'", - 'different' => "doit être différent de '%s'", - 'accepted' => "doit être accepté", - 'numeric' => "doit être numérique", - 'integer' => "doit être un entier", - 'length' => "doit être plus long que %d", - 'min' => "doit être plus grand que %s", - 'max' => "doit être plus petit que %s", - 'listContains' => "contient une valeur non valide", - 'in' => "contient une valeur non valide", - 'notIn' => "contient une valeur non valide", - 'ip' => "n'est pas une adresse IP valide", - 'email' => "n'est pas une adresse email valide", - 'url' => "n'est pas une URL", - 'urlActive' => "doit être un domaine actif", - 'alpha' => "doit contenir uniquement les lettres a-z", - 'alphaNum' => "doit contenir uniquement des lettres de a-z et/ou des chiffres 0-9", - 'slug' => "doit contenir uniquement des lettres de a-z, des chiffres 0-9, des tirets et des traits soulignés", - 'regex' => "contient des caractères invalides", - 'date' => "n'est pas une date valide", - 'dateFormat' => "doit être une date avec le format '%s'", - 'dateBefore' => "doit être une date avant '%s'", - 'dateAfter' => "doit être une date après '%s'", - 'contains' => "doit contenir %s", - 'boolean' => "doit être un booléen", - 'lengthBetween' => "doit être entre %d et %d caractères", - 'creditCard' => "doit être un numéro de carte de crédit valide", - 'lengthMin' => "doit avoir au moins %d caractères", - 'lengthMax' => "ne doit pas dépasser %d caractères", - 'instanceOf' => "doit être une instance de '%s'", - "containsUnique" => "doit contenir des élements unique", - "requiredWith" => "est requis", - "requiredWithout" => "est requis", - "subset" => "contient un élement qui n'est pas dans la liste", - "arrayHasKeys" => "ne contient pas toutes les clés requises" +return array( + 'required' => "est obligatoire", + 'equals' => "doit être identique à '%s'", + 'different' => "doit être différent de '%s'", + 'accepted' => "doit être accepté", + 'numeric' => "doit être numérique", + 'integer' => "doit être un entier", + 'length' => "doit être plus long que %d", + 'min' => "doit être plus grand que %s", + 'max' => "doit être plus petit que %s", + 'listContains' => "contient une valeur non valide", + 'in' => "contient une valeur non valide", + 'notIn' => "contient une valeur non valide", + 'ip' => "n'est pas une adresse IP valide", + 'email' => "n'est pas une adresse email valide", + 'url' => "n'est pas une URL", + 'urlActive' => "doit être un domaine actif", + 'alpha' => "doit contenir uniquement les lettres a-z", + 'alphaNum' => "doit contenir uniquement des lettres de a-z et/ou des chiffres 0-9", + 'slug' => "doit contenir uniquement des lettres de a-z, des chiffres 0-9, des tirets et des traits soulignés", + 'regex' => "contient des caractères invalides", + 'date' => "n'est pas une date valide", + 'dateFormat' => "doit être une date avec le format '%s'", + 'dateBefore' => "doit être une date avant '%s'", + 'dateAfter' => "doit être une date après '%s'", + 'contains' => "doit contenir %s", + 'boolean' => "doit être un booléen", + 'lengthBetween' => "doit être entre %d et %d caractères", + 'creditCard' => "doit être un numéro de carte de crédit valide", + 'lengthMin' => "doit avoir au moins %d caractères", + 'lengthMax' => "ne doit pas dépasser %d caractères", + 'instanceOf' => "doit être une instance de '%s'", + "containsUnique" => "doit contenir des élements unique", + "requiredWith" => "est requis", + "requiredWithout" => "est requis", + "subset" => "contient un élement qui n'est pas dans la liste", + "arrayHasKeys" => "ne contient pas toutes les clés requises" ); diff --git a/src/validator/lang/id.php b/src/validator/lang/id.php index 2df9a61..76e3635 100644 --- a/src/validator/lang/id.php +++ b/src/validator/lang/id.php @@ -1,34 +1,34 @@ "harus diisi", - 'equals' => "harus sama dengan '%s'", - 'different' => "harus berbeda dengan '%s'", - 'accepted' => "harus diterima (accepted)", - 'numeric' => "harus berupa nomor/angka", - 'integer' => "harus berupa nilai integer", - 'length' => "harus lebih panjang dari %d", - 'min' => "harus lebih besar dari %s", - 'max' => "harus kurang dari %s", - 'listContains' => "berisi nilai/value yang tidak valid", - 'in' => "berisi nilai/value yang tidak valid", - 'notIn' => "berisi nilai/value yang tidak valid", - 'ip' => "format alamat IP tidak benar", - 'email' => "format alamat email tidak benar", - 'url' => "bukan format URL yang benar", - 'urlActive' => "harus berupa domain aktif", - 'alpha' => "hanya boleh menggunakan huruf a-z", - 'alphaNum' => "hanya boleh menggunakan huruf a-z dan atau nomor 0-9", - 'slug' => "hanya boleh menggunakan huruf a-z, nomor 0-9, tanda minus (-), dan uderscore atau strip bawah (_)", - 'regex' => "berisi karakter yang tidak valid", - 'date' => "format tanggal tidak valid", - 'dateFormat' => "harus berupa tanggal dengan format '%s'", - 'dateBefore' => "tanggal harus sebelum tanggal '%s'", - 'dateAfter' => "tanggal harus sesudah tanggal '%s'", - 'contains' => "harus berisi %s", - 'boolean' => "harus berupa nilai boolean", + 'required' => "harus diisi", + 'equals' => "harus sama dengan '%s'", + 'different' => "harus berbeda dengan '%s'", + 'accepted' => "harus diterima (accepted)", + 'numeric' => "harus berupa nomor/angka", + 'integer' => "harus berupa nilai integer", + 'length' => "harus lebih panjang dari %d", + 'min' => "harus lebih besar dari %s", + 'max' => "harus kurang dari %s", + 'listContains' => "berisi nilai/value yang tidak valid", + 'in' => "berisi nilai/value yang tidak valid", + 'notIn' => "berisi nilai/value yang tidak valid", + 'ip' => "format alamat IP tidak benar", + 'email' => "format alamat email tidak benar", + 'url' => "bukan format URL yang benar", + 'urlActive' => "harus berupa domain aktif", + 'alpha' => "hanya boleh menggunakan huruf a-z", + 'alphaNum' => "hanya boleh menggunakan huruf a-z dan atau nomor 0-9", + 'slug' => "hanya boleh menggunakan huruf a-z, nomor 0-9, tanda minus (-), dan uderscore atau strip bawah (_)", + 'regex' => "berisi karakter yang tidak valid", + 'date' => "format tanggal tidak valid", + 'dateFormat' => "harus berupa tanggal dengan format '%s'", + 'dateBefore' => "tanggal harus sebelum tanggal '%s'", + 'dateAfter' => "tanggal harus sesudah tanggal '%s'", + 'contains' => "harus berisi %s", + 'boolean' => "harus berupa nilai boolean", 'lengthBetween' => "harus diantara karakter %d dan %d", - 'creditCard' => "nomor kartu kredit harus valid", - "lengthMin" => "minimal berisi %d karakter", - "lengthMax" => "maksimal berisi %d karakter" + 'creditCard' => "nomor kartu kredit harus valid", + "lengthMin" => "minimal berisi %d karakter", + "lengthMax" => "maksimal berisi %d karakter" ); diff --git a/src/validator/lang/it.php b/src/validator/lang/it.php index 467746b..7d3ee82 100644 --- a/src/validator/lang/it.php +++ b/src/validator/lang/it.php @@ -1,35 +1,35 @@ "è obbligatorio", - 'equals' => "deve essere uguale a '%s'", - 'different' => "deve essere differente da '%s'", - 'accepted' => "deve essere accettato", - 'numeric' => "deve essere numerico", - 'integer' => "deve essere un intero", - 'length' => "deve avere una lunghezza di %d", - 'min' => "deve essere superiore a %s", - 'max' => "deve essere inferiore a %s", - 'listContains' => "contiene un valore non valido", - 'in' => "contiene un valore non valido", - 'notIn' => "contiene un valore non valido", - 'ip' => "non è un indirizzo IP valido", - 'email' => "non è un indirizzo email valido", - 'url' => "non è una URL", - 'urlActive' => "deve essere un dominio attivo", - 'alpha' => "deve contenere solamente lettere (a-z)", - 'alphaNum' => "deve contenere solamente lettere (a-z) e/o numeri (0-9)", - 'slug' => "deve contenere solamente lettere (a-z), numeri (0-9), trattini (-) e trattini bassi (_)", - 'regex' => "contiene caratteri non validi", - 'date' => "non è una data valida", - 'dateFormat' => "deve essere una data nel formato '%s'", - 'dateBefore' => "deve essere una data precedente al '%s'", - 'dateAfter' => "deve essere una data successiva al '%s'", - 'contains' => "deve contenere %s", - 'boolean' => "deve essere un booleano", + 'required' => "è obbligatorio", + 'equals' => "deve essere uguale a '%s'", + 'different' => "deve essere differente da '%s'", + 'accepted' => "deve essere accettato", + 'numeric' => "deve essere numerico", + 'integer' => "deve essere un intero", + 'length' => "deve avere una lunghezza di %d", + 'min' => "deve essere superiore a %s", + 'max' => "deve essere inferiore a %s", + 'listContains' => "contiene un valore non valido", + 'in' => "contiene un valore non valido", + 'notIn' => "contiene un valore non valido", + 'ip' => "non è un indirizzo IP valido", + 'email' => "non è un indirizzo email valido", + 'url' => "non è una URL", + 'urlActive' => "deve essere un dominio attivo", + 'alpha' => "deve contenere solamente lettere (a-z)", + 'alphaNum' => "deve contenere solamente lettere (a-z) e/o numeri (0-9)", + 'slug' => "deve contenere solamente lettere (a-z), numeri (0-9), trattini (-) e trattini bassi (_)", + 'regex' => "contiene caratteri non validi", + 'date' => "non è una data valida", + 'dateFormat' => "deve essere una data nel formato '%s'", + 'dateBefore' => "deve essere una data precedente al '%s'", + 'dateAfter' => "deve essere una data successiva al '%s'", + 'contains' => "deve contenere %s", + 'boolean' => "deve essere un booleano", 'lengthBetween' => "deve essere compreso tra %d e %d caratteri", - 'creditCard' => "deve essere un numero di carta di credito valido", - 'lengthMin' => "deve essere lungo almeno %d caratteri", - 'lengthMax' => "non deve superare %d caratteri", - 'instanceOf' => "deve essere un'istanza di '%s'", + 'creditCard' => "deve essere un numero di carta di credito valido", + 'lengthMin' => "deve essere lungo almeno %d caratteri", + 'lengthMax' => "non deve superare %d caratteri", + 'instanceOf' => "deve essere un'istanza di '%s'", ); diff --git a/src/validator/lang/ja.php b/src/validator/lang/ja.php index b7b20b1..d5200c4 100644 --- a/src/validator/lang/ja.php +++ b/src/validator/lang/ja.php @@ -1,42 +1,42 @@ "を入力してください", - 'equals' => "は「%s」と同じ内容を入力してください", - 'different' => "は「%s」と異なる内容を入力してください", - 'accepted' => "に同意してください", - 'numeric' => "は数値を入力してください", - 'integer' => "は半角数字で入力してください", - 'length' => "は%d文字で入力してください", - 'min' => "には%sより大きな値を入力してください", - 'max' => "には%sより小さな値を入力してください", - 'listContains' => "には選択できない値が含まれています", - 'in' => "には選択できない値が含まれています", - 'notIn' => "には選択できない値が含まれています", - 'ip' => "はIPアドレスの書式として正しくありません", - 'ipv4' => "はIPv4のIPアドレスの書式として正しくありません", - 'ipv6' => "はIPv6のIPアドレスの書式として正しくありません", - 'email' => "はメールアドレスの書式として正しくありません", - 'url' => "はURLの書式として正しくありません", - 'urlActive' => "はアクティブなドメインではありません", - 'alpha' => "は半角英字で入力してください", - 'alphaNum' => "は半角英数字で入力してください", - 'slug' => "は半角英数字、もしくは「-」「_」の文字で入力してください", - 'regex' => "の書式が正しくありません", - 'date' => "は日付の書式として正しくありません", - 'dateFormat' => "は「%s」の書式で日付を入力してください", - 'dateBefore' => "は「%s」以前の日付を入力してください", - 'dateAfter' => "は「%s」以後の日付を入力してください", - 'contains' => "は「%s」を含んでいなければいけません", - 'boolean' => "は真偽値である必要があります", - 'lengthBetween' => "は%d〜%d文字で入力してください", - 'creditCard' => "はクレジットカード番号の書式として正しくありません", - 'lengthMin' => "は%d文字以上入力してください", - 'lengthMax' => "は%d文字以内で入力してください", - 'instanceOf' => "は「%s」のインスタンスではありません", - 'containsUnique' => "は重複のないように入力してください", - 'requiredWith' => "を入力してください", + 'required' => "を入力してください", + 'equals' => "は「%s」と同じ内容を入力してください", + 'different' => "は「%s」と異なる内容を入力してください", + 'accepted' => "に同意してください", + 'numeric' => "は数値を入力してください", + 'integer' => "は半角数字で入力してください", + 'length' => "は%d文字で入力してください", + 'min' => "には%sより大きな値を入力してください", + 'max' => "には%sより小さな値を入力してください", + 'listContains' => "には選択できない値が含まれています", + 'in' => "には選択できない値が含まれています", + 'notIn' => "には選択できない値が含まれています", + 'ip' => "はIPアドレスの書式として正しくありません", + 'ipv4' => "はIPv4のIPアドレスの書式として正しくありません", + 'ipv6' => "はIPv6のIPアドレスの書式として正しくありません", + 'email' => "はメールアドレスの書式として正しくありません", + 'url' => "はURLの書式として正しくありません", + 'urlActive' => "はアクティブなドメインではありません", + 'alpha' => "は半角英字で入力してください", + 'alphaNum' => "は半角英数字で入力してください", + 'slug' => "は半角英数字、もしくは「-」「_」の文字で入力してください", + 'regex' => "の書式が正しくありません", + 'date' => "は日付の書式として正しくありません", + 'dateFormat' => "は「%s」の書式で日付を入力してください", + 'dateBefore' => "は「%s」以前の日付を入力してください", + 'dateAfter' => "は「%s」以後の日付を入力してください", + 'contains' => "は「%s」を含んでいなければいけません", + 'boolean' => "は真偽値である必要があります", + 'lengthBetween' => "は%d〜%d文字で入力してください", + 'creditCard' => "はクレジットカード番号の書式として正しくありません", + 'lengthMin' => "は%d文字以上入力してください", + 'lengthMax' => "は%d文字以内で入力してください", + 'instanceOf' => "は「%s」のインスタンスではありません", + 'containsUnique' => "は重複のないように入力してください", + 'requiredWith' => "を入力してください", 'requiredWithout' => "を入力してください", - 'subset' => "には選択できない値が含まれています", - 'arrayHasKeys' => "の必要な項目が選択されていません", + 'subset' => "には選択できない値が含まれています", + 'arrayHasKeys' => "の必要な項目が選択されていません", ); diff --git a/src/validator/lang/ko.php b/src/validator/lang/ko.php index c4d42bf..0e8c62a 100644 --- a/src/validator/lang/ko.php +++ b/src/validator/lang/ko.php @@ -1,35 +1,35 @@ "을(를) 입력해야 합니다.", - 'equals' => "은(는) '%s'와(과) 같아야 합니다.", - 'different' => "은(는) '%s'와(과) 달라야 합니다.", - 'accepted' => "을(를) 동의해야 합니다.", - 'numeric' => "은(는) 숫자여야 합니다.", - 'integer' => "은(는) 정수여야 합니다.", - 'length' => "의 길이는 %d 이어야 합니다.", - 'min' => "은(는) %s 이상이어야 합니다.", - 'max' => "은(는) %s 이하여야 합니다.", - 'listContains' => "은(는) 올바르지 않은 값을 포함하고 있습니다.", - 'in' => "은(는) 올바르지 않은 값을 포함하고 있습니다.", - 'notIn' => "은(는) 올바르지 않은 값을 포함하고 있습니다.", - 'ip' => "은(는) 올바르지 않은 IP입니다.", - 'email' => "은(는) 올바르지 않은 email입니다.", - 'url' => "은(는) 올바르지 않은 URL입니다.", - 'urlActive' => "은(는) 접속 가능한 도메인이어야 합니다.", - 'alpha' => "은(는) 영문자(a-z)로만 이루어져야 합니다.", - 'alphaNum' => "은(는) 영문자(a-z)와 숫자(0-9)로만 이루어져야 합니다.", - 'slug' => "은(는) 영문자(a-z)와 숫자(0-9), 특수문자 -와 _로만 이루어져야 합니다.", - 'regex' => "은(는) 올바르지 않은 문자를 포함하고 있습니다.", - 'date' => "은(는) 올바르지 않은 날짜입니다.", - 'dateFormat' => "은(는) '%s' 형태의 날짜여야 합니다.", - 'dateBefore' => "은(는) '%s' 보다 이전이어야 합니다.", - 'dateAfter' => "은(는) '%s' 보다 이후여야 합니다.", - 'contains' => "은(는) '%s'을(를) 포함해야 합니다.", - 'boolean' => "은(는) boolean이어야 합니다.", + 'required' => "을(를) 입력해야 합니다.", + 'equals' => "은(는) '%s'와(과) 같아야 합니다.", + 'different' => "은(는) '%s'와(과) 달라야 합니다.", + 'accepted' => "을(를) 동의해야 합니다.", + 'numeric' => "은(는) 숫자여야 합니다.", + 'integer' => "은(는) 정수여야 합니다.", + 'length' => "의 길이는 %d 이어야 합니다.", + 'min' => "은(는) %s 이상이어야 합니다.", + 'max' => "은(는) %s 이하여야 합니다.", + 'listContains' => "은(는) 올바르지 않은 값을 포함하고 있습니다.", + 'in' => "은(는) 올바르지 않은 값을 포함하고 있습니다.", + 'notIn' => "은(는) 올바르지 않은 값을 포함하고 있습니다.", + 'ip' => "은(는) 올바르지 않은 IP입니다.", + 'email' => "은(는) 올바르지 않은 email입니다.", + 'url' => "은(는) 올바르지 않은 URL입니다.", + 'urlActive' => "은(는) 접속 가능한 도메인이어야 합니다.", + 'alpha' => "은(는) 영문자(a-z)로만 이루어져야 합니다.", + 'alphaNum' => "은(는) 영문자(a-z)와 숫자(0-9)로만 이루어져야 합니다.", + 'slug' => "은(는) 영문자(a-z)와 숫자(0-9), 특수문자 -와 _로만 이루어져야 합니다.", + 'regex' => "은(는) 올바르지 않은 문자를 포함하고 있습니다.", + 'date' => "은(는) 올바르지 않은 날짜입니다.", + 'dateFormat' => "은(는) '%s' 형태의 날짜여야 합니다.", + 'dateBefore' => "은(는) '%s' 보다 이전이어야 합니다.", + 'dateAfter' => "은(는) '%s' 보다 이후여야 합니다.", + 'contains' => "은(는) '%s'을(를) 포함해야 합니다.", + 'boolean' => "은(는) boolean이어야 합니다.", 'lengthBetween' => "의 길이는 %d에서 %d 사이여야 합니다.", - 'creditCard' => "은(는) 올바른 신용카드 번호가 아닙니다.", - 'lengthMin' => "의 길이는 %d 이상이어야 합니다.", - 'lengthMax' => "의 길이는 %d을(를) 넘을 수 없습니다.", - 'instanceOf' => "는 '%s'의 객체여야 합니다." + 'creditCard' => "은(는) 올바른 신용카드 번호가 아닙니다.", + 'lengthMin' => "의 길이는 %d 이상이어야 합니다.", + 'lengthMax' => "의 길이는 %d을(를) 넘을 수 없습니다.", + 'instanceOf' => "는 '%s'의 객체여야 합니다." ); diff --git a/src/validator/lang/lt.php b/src/validator/lang/lt.php index 4404311..a3f7dbf 100644 --- a/src/validator/lang/lt.php +++ b/src/validator/lang/lt.php @@ -1,38 +1,39 @@ "yra privalomas", - 'equals' => "reikšmė turi būti tokia pati, kaip „%s“", - 'different' => "turi būti kitokia, nei „%s“", - 'accepted' => "turi būti priimta", - 'numeric' => "turi būti sveikasis skaičius", - 'integer' => "turi būti skaičius", - 'length' => "turi būti %d ženklų ilgio", - 'min' => "turi būti bent %s", - 'max' => "turi būti ne daugiau kaip %s", - 'listContains' => "turi neteisingą vertę", - 'in' => "turi neteisingą vertę", - 'notIn' => "turi neteisingą vertę", - 'ip' => "nėra teisingas IP adresas", - 'ipv4' => "nėra teisingas IPv4 adresas", - 'ipv6' => "nėra teisingas IPv6 adresas", - 'email' => "nėra teisingas el. pašto adresas", - 'url' => "nėra teisingas URL", - 'urlActive' => "turi būti aktyvus domenas", - 'alpha' => "turi turėti tik raides a-ž", - 'alphaNum' => "turi turėti tik raides a-ž ir/ar skaičius 0-9", - 'slug' => "turi turėti tik raides a-ž, skaičius 0-9, brukšnelius ir apatinius brukšnelius", - 'regex' => "yra neteisingų ženklų", - 'date' => "nėra teisinga data", - 'dateFormat' => "turi būti „%s“ formato data", - 'dateBefore' => "turi būti data, ankstesnė nei „%s“", - 'dateAfter' => "turi būti data, vėlesnė nei „%s“", - 'contains' => "turi turėti %s", - 'boolean' => "turi būti būlio (taip/ne) tipo", + 'required' => "yra privalomas", + 'equals' => "reikšmė turi būti tokia pati, kaip „%s“", + 'different' => "turi būti kitokia, nei „%s“", + 'accepted' => "turi būti priimta", + 'numeric' => "turi būti sveikasis skaičius", + 'integer' => "turi būti skaičius", + 'length' => "turi būti %d ženklų ilgio", + 'min' => "turi būti bent %s", + 'max' => "turi būti ne daugiau kaip %s", + 'listContains' => "turi neteisingą vertę", + 'in' => "turi neteisingą vertę", + 'notIn' => "turi neteisingą vertę", + 'ip' => "nėra teisingas IP adresas", + 'ipv4' => "nėra teisingas IPv4 adresas", + 'ipv6' => "nėra teisingas IPv6 adresas", + 'email' => "nėra teisingas el. pašto adresas", + 'url' => "nėra teisingas URL", + 'urlActive' => "turi būti aktyvus domenas", + 'alpha' => "turi turėti tik raides a-ž", + 'alphaNum' => "turi turėti tik raides a-ž ir/ar skaičius 0-9", + 'slug' => "turi turėti tik raides a-ž, skaičius 0-9, brukšnelius ir apatinius brukšnelius", + 'regex' => "yra neteisingų ženklų", + 'date' => "nėra teisinga data", + 'dateFormat' => "turi būti „%s“ formato data", + 'dateBefore' => "turi būti data, ankstesnė nei „%s“", + 'dateAfter' => "turi būti data, vėlesnė nei „%s“", + 'contains' => "turi turėti %s", + 'boolean' => "turi būti būlio (taip/ne) tipo", 'lengthBetween' => "turi būti nuo %d iki %d ilgio", - 'creditCard' => "turi būti teisingas kreditinės kortelės numeris", - 'lengthMin' => "turi būti bent %d ženklų ilgio", - 'lengthMax' => "turi būti ne ilgesnis nei %d ženklų", - 'instanceOf' => "turi būti „%s“ atvejis", + 'creditCard' => "turi būti teisingas kreditinės kortelės numeris", + 'lengthMin' => "turi būti bent %d ženklų ilgio", + 'lengthMax' => "turi būti ne ilgesnis nei %d ženklų", + 'instanceOf' => "turi būti „%s“ atvejis", 'containsUnique' => "turi turėti tik unikalius elementus", - 'subset' => "turi elementą, kurio nėra sąraše" + 'subset' => "turi elementą, kurio nėra sąraše" ); diff --git a/src/validator/lang/lv.php b/src/validator/lang/lv.php index fef222a..83ef78d 100644 --- a/src/validator/lang/lv.php +++ b/src/validator/lang/lv.php @@ -1,32 +1,32 @@ "ir obligāts lauks", - 'equals' => "jāsakrīt ar '%s'", - 'different' => "nedrīkst sakrist ar '%s' lauku", - 'accepted' => "laukam jābūt apstiprinātam", - 'numeric' => "jābūt skaitliskai vērtībai", - 'integer' => "jābūt ciparam (0-9)", - 'length' => "nedrīkst būt garāks par %d simboliem", - 'min' => "jābūt garākam par %s simboliem", - 'max' => "jābūt īsākam par %s simboliem", - 'listContains' => "lauks satur nederīgu vērtību", - 'in' => "lauks satur nederīgu vērtību", - 'notIn' => "lauks satur nederīgu vērtību", - 'ip' => " lauks nav derīga IP adrese", - 'email' => "lauks nav norādīta derīga epasta adrese", - 'url' => "lauks nav tīmekļa saite", - 'urlActive' => "saite neatrodas esošajā domēna vārdā", - 'alpha' => "lauks var saturēt tikai alfabēta burtus a-z", - 'alphaNum' => "lauks var saturēt tikai alfabēta burtus un/vai ciparus 0-9", - 'slug' => "lauks var saturēt tikai alfabēta burtus un/vai ciparus 0-9, domuzīmes and zemsvītras", - 'regex' => "lauks satur nederīgus simbolus", - 'date' => "lauks ir nederīgā datuma formātā", - 'dateFormat' => "laukam jābūt datuma formātā '%s'", - 'dateBefore' => "lauka datumam jābūt pirms '%s'", - 'dateAfter' => "lauka datumam jābūt pēc '%s'", - 'contains' => "laukam jāsatur %s", - 'boolean' => "laukam jābūt ir/nav vērtībai", + 'required' => "ir obligāts lauks", + 'equals' => "jāsakrīt ar '%s'", + 'different' => "nedrīkst sakrist ar '%s' lauku", + 'accepted' => "laukam jābūt apstiprinātam", + 'numeric' => "jābūt skaitliskai vērtībai", + 'integer' => "jābūt ciparam (0-9)", + 'length' => "nedrīkst būt garāks par %d simboliem", + 'min' => "jābūt garākam par %s simboliem", + 'max' => "jābūt īsākam par %s simboliem", + 'listContains' => "lauks satur nederīgu vērtību", + 'in' => "lauks satur nederīgu vērtību", + 'notIn' => "lauks satur nederīgu vērtību", + 'ip' => " lauks nav derīga IP adrese", + 'email' => "lauks nav norādīta derīga epasta adrese", + 'url' => "lauks nav tīmekļa saite", + 'urlActive' => "saite neatrodas esošajā domēna vārdā", + 'alpha' => "lauks var saturēt tikai alfabēta burtus a-z", + 'alphaNum' => "lauks var saturēt tikai alfabēta burtus un/vai ciparus 0-9", + 'slug' => "lauks var saturēt tikai alfabēta burtus un/vai ciparus 0-9, domuzīmes and zemsvītras", + 'regex' => "lauks satur nederīgus simbolus", + 'date' => "lauks ir nederīgā datuma formātā", + 'dateFormat' => "laukam jābūt datuma formātā '%s'", + 'dateBefore' => "lauka datumam jābūt pirms '%s'", + 'dateAfter' => "lauka datumam jābūt pēc '%s'", + 'contains' => "laukam jāsatur %s", + 'boolean' => "laukam jābūt ir/nav vērtībai", 'lengthBetween' => "lauka garumam jābūt no %d līdz %d simbolu garam", - 'creditCard' => "laukam jābūt derīgam kredītkartes numuram" + 'creditCard' => "laukam jābūt derīgam kredītkartes numuram" ); diff --git a/src/validator/lang/nb.php b/src/validator/lang/nb.php index d5d2d5e..66507b6 100644 --- a/src/validator/lang/nb.php +++ b/src/validator/lang/nb.php @@ -1,39 +1,40 @@ "er påkrevd", - 'equals' => "må være lik '%s'", - 'different' => "må være annerledes enn '%s'", - 'accepted' => "må aksepteres", - 'numeric' => "må være numerisk", - 'integer' => "må være et heltall", - 'length' => "må være %d tegn langt", - 'min' => "må være minst %s", - 'max' => "må ikke være mer enn %s", - 'listContains' => "inneholder ugyldig verdi", - 'in' => "inneholder ugyldig verdi", - 'notIn' => "inneholder ugyldig verdi", - 'ip' => "er ikke en gyldig IP adresse", - 'ipv4' => "er ikke en gyldig IPv4 adresse", - 'ipv6' => "er ikke en gyldig IPv6 adresse", - 'email' => "er ikke en gyldig e-postadresse", - 'url' => "er ikke en gyldig URL", - 'urlActive' => "må være et aktivt domene", - 'alpha' => "må bare innholde bokstaver a-z", - 'alphaNum' => "må bare innholde bokstaver a-z og/eller tall 0-9", - 'slug' => "må bare innholde bokstaver a-z og/eller tall 0-9, bindestreker og understreker", - 'regex' => "inneholder ulovlige tegn", - 'date' => "er ikke en gyldig dato", - 'dateFormat' => "må være en dato med format '%s'", - 'dateBefore' => "må være en dato før '%s'", - 'dateAfter' => "må være en dato etter '%s'", - 'contains' => "må inneholde %s", - 'boolean' => "må være en boolsk verdi", + 'required' => "er påkrevd", + 'equals' => "må være lik '%s'", + 'different' => "må være annerledes enn '%s'", + 'accepted' => "må aksepteres", + 'numeric' => "må være numerisk", + 'integer' => "må være et heltall", + 'length' => "må være %d tegn langt", + 'min' => "må være minst %s", + 'max' => "må ikke være mer enn %s", + 'listContains' => "inneholder ugyldig verdi", + 'in' => "inneholder ugyldig verdi", + 'notIn' => "inneholder ugyldig verdi", + 'ip' => "er ikke en gyldig IP adresse", + 'ipv4' => "er ikke en gyldig IPv4 adresse", + 'ipv6' => "er ikke en gyldig IPv6 adresse", + 'email' => "er ikke en gyldig e-postadresse", + 'url' => "er ikke en gyldig URL", + 'urlActive' => "må være et aktivt domene", + 'alpha' => "må bare innholde bokstaver a-z", + 'alphaNum' => "må bare innholde bokstaver a-z og/eller tall 0-9", + 'slug' => "må bare innholde bokstaver a-z og/eller tall 0-9, bindestreker og understreker", + 'regex' => "inneholder ulovlige tegn", + 'date' => "er ikke en gyldig dato", + 'dateFormat' => "må være en dato med format '%s'", + 'dateBefore' => "må være en dato før '%s'", + 'dateAfter' => "må være en dato etter '%s'", + 'contains' => "må inneholde %s", + 'boolean' => "må være en boolsk verdi", 'lengthBetween' => "må være mellom %d og %d tegn", - 'creditCard' => "må være et gyldig kredittkortnummer", - 'lengthMin' => "må være minst %d tegn langt", - 'lengthMax' => "må ikke overstige %d tegn", - 'instanceOf' => "må være en instans av '%s'", - 'containsUnique'=> "må inneholde kun unike elementer", - 'subset' => "inneholder et element som ikke er i listen" + 'creditCard' => "må være et gyldig kredittkortnummer", + 'lengthMin' => "må være minst %d tegn langt", + 'lengthMax' => "må ikke overstige %d tegn", + 'instanceOf' => "må være en instans av '%s'", + 'containsUnique' => "må inneholde kun unike elementer", + 'subset' => "inneholder et element som ikke er i listen" ); \ No newline at end of file diff --git a/src/validator/lang/nl.php b/src/validator/lang/nl.php index 7d7fa8f..49381cf 100644 --- a/src/validator/lang/nl.php +++ b/src/validator/lang/nl.php @@ -1,35 +1,35 @@ "is verplicht", - 'equals' => "moet gelijk zijn aan '%s'", - 'different' => "moet verschillend zijn van '%s'", - 'accepted' => "moet aanvaard worden", - 'numeric' => "moet numeriek zijn", - 'integer' => "moet een cijfer zijn", - 'length' => "moet minstens %d karakters lang zijn", - 'min' => "moet minstens %s zijn", - 'max' => "mag niet meer zijn dan %s", - 'listContains' => "bevat een ongeldige waarde", - 'in' => "bevat een ongeldige waarde", - 'notIn' => "bevat een ongeldige waarde", - 'ip' => "is geen geldig IP-adres", - 'email' => "is geen geldig e-mailadres", - 'url' => "is geen geldige URL", - 'urlActive' => "moet een actief domein zijn", - 'alpha' => "mag enkel letters (a-z) bevatten", - 'alphaNum' => "mag enkel letters (a-z) en/of cijfers (0-9) bevatten", - 'slug' => "mag enkel letters (a-z), cijfers (0-9) en liggende streepjes (_,-) bevatten", - 'regex' => "bevat ongeldige karakters", - 'date' => "is geen geldige datum", - 'dateFormat' => "moet een datum zijn in het formaat '%s'", - 'dateBefore' => "moet een datum voor '%s' zijn", - 'dateAfter' => "moet een datum na '%s' zijn", - 'contains' => "moet '%s' bevatten", - 'boolean' => "moet een booleaanse waarde zijn", + 'required' => "is verplicht", + 'equals' => "moet gelijk zijn aan '%s'", + 'different' => "moet verschillend zijn van '%s'", + 'accepted' => "moet aanvaard worden", + 'numeric' => "moet numeriek zijn", + 'integer' => "moet een cijfer zijn", + 'length' => "moet minstens %d karakters lang zijn", + 'min' => "moet minstens %s zijn", + 'max' => "mag niet meer zijn dan %s", + 'listContains' => "bevat een ongeldige waarde", + 'in' => "bevat een ongeldige waarde", + 'notIn' => "bevat een ongeldige waarde", + 'ip' => "is geen geldig IP-adres", + 'email' => "is geen geldig e-mailadres", + 'url' => "is geen geldige URL", + 'urlActive' => "moet een actief domein zijn", + 'alpha' => "mag enkel letters (a-z) bevatten", + 'alphaNum' => "mag enkel letters (a-z) en/of cijfers (0-9) bevatten", + 'slug' => "mag enkel letters (a-z), cijfers (0-9) en liggende streepjes (_,-) bevatten", + 'regex' => "bevat ongeldige karakters", + 'date' => "is geen geldige datum", + 'dateFormat' => "moet een datum zijn in het formaat '%s'", + 'dateBefore' => "moet een datum voor '%s' zijn", + 'dateAfter' => "moet een datum na '%s' zijn", + 'contains' => "moet '%s' bevatten", + 'boolean' => "moet een booleaanse waarde zijn", 'lengthBetween' => "moet tussen %d en %d karakters lang zijn", - 'creditCard' => "moet een geldig kredietkaartnummer zijn", - "lengthMin" => "moet meer dan %d karakters lang zijn", - "lengthMax" => "mag niet meer dan %d karakters lang zijn", - "instanceOf" => "moet een instantie zijn van '%s'" + 'creditCard' => "moet een geldig kredietkaartnummer zijn", + "lengthMin" => "moet meer dan %d karakters lang zijn", + "lengthMax" => "mag niet meer dan %d karakters lang zijn", + "instanceOf" => "moet een instantie zijn van '%s'" ); diff --git a/src/validator/lang/nn.php b/src/validator/lang/nn.php index 1fa3b6b..02ee9be 100644 --- a/src/validator/lang/nn.php +++ b/src/validator/lang/nn.php @@ -1,35 +1,35 @@ "er nødvendig", - 'equals' => "må være de samme som '%s'", - 'different' => "må være annerledes enn '%s'", - 'accepted' => "må aksepteres", - 'numeric' => "må være numerisk", - 'integer' => "må være et heltall", - 'length' => "må være %d tegn", - 'min' => "må være minst %s", - 'max' => "må ikke være mer enn %s", - 'listContains' => "inneholder ugyldig verdi", - 'in' => "inneholder ugyldig verdi", - 'notIn' => "inneholder ugyldig verdi", - 'ip' => "er ikkje ein gyldig IP Adresse", - 'email' => "er ikkje ein gyldig E-post adresse", - 'url' => "er ikkje ein gyldig URL", - 'urlActive' => "må være eit aktivt domene", - 'alpha' => "må bare innholde bokstaver a-z", - 'alphaNum' => "må bare innholde bokstaver a-z og/eller tall 0-9", - 'slug' => "må bare innholde bokstaver a-z og/eller tall 0-9, bindestreker og understreker", - 'regex' => "inneholder ulovlige tegn", - 'date' => "er ikkje ein gylid dato", - 'dateFormat' => "må være ein dato med formatet '%s'", - 'dateBefore' => "må være ein dato før '%s'", - 'dateAfter' => "må være ein dato etter '%s'", - 'contains' => "må inneholde %s", - 'boolean' => "må være ein boolsk verdi", + 'required' => "er nødvendig", + 'equals' => "må være de samme som '%s'", + 'different' => "må være annerledes enn '%s'", + 'accepted' => "må aksepteres", + 'numeric' => "må være numerisk", + 'integer' => "må være et heltall", + 'length' => "må være %d tegn", + 'min' => "må være minst %s", + 'max' => "må ikke være mer enn %s", + 'listContains' => "inneholder ugyldig verdi", + 'in' => "inneholder ugyldig verdi", + 'notIn' => "inneholder ugyldig verdi", + 'ip' => "er ikkje ein gyldig IP Adresse", + 'email' => "er ikkje ein gyldig E-post adresse", + 'url' => "er ikkje ein gyldig URL", + 'urlActive' => "må være eit aktivt domene", + 'alpha' => "må bare innholde bokstaver a-z", + 'alphaNum' => "må bare innholde bokstaver a-z og/eller tall 0-9", + 'slug' => "må bare innholde bokstaver a-z og/eller tall 0-9, bindestreker og understreker", + 'regex' => "inneholder ulovlige tegn", + 'date' => "er ikkje ein gylid dato", + 'dateFormat' => "må være ein dato med formatet '%s'", + 'dateBefore' => "må være ein dato før '%s'", + 'dateAfter' => "må være ein dato etter '%s'", + 'contains' => "må inneholde %s", + 'boolean' => "må være ein boolsk verdi", 'lengthBetween' => "må være imellom %d og %d tegn", - 'creditCard' => "må være et gyldig kredittkortnummer", - 'lengthMin' => "må være minst %d tegn", - 'lengthMax' => "må ikkje overstige %d tegn", - 'instanceOf' => "må være ein instans av '%s'" + 'creditCard' => "må være et gyldig kredittkortnummer", + 'lengthMin' => "må være minst %d tegn", + 'lengthMax' => "må ikkje overstige %d tegn", + 'instanceOf' => "må være ein instans av '%s'" ); diff --git a/src/validator/lang/pl.php b/src/validator/lang/pl.php index 0f8f2e0..e41d278 100644 --- a/src/validator/lang/pl.php +++ b/src/validator/lang/pl.php @@ -1,35 +1,35 @@ "jest wymagane", - 'equals' => "musi być takie same jak '%s'", - 'different' => "musi być różne od '%s'", - 'accepted' => "musi być zaakceptowane", - 'numeric' => "musi być liczbą", - 'integer' => "musi być liczbą całkowitą", - 'length' => "musi być dłuższe niż %d", - 'min' => "musi być przynajmniej %s", - 'max' => "nie może być większe niż %s", - 'listContains' => "zawiera nieprawidłową wartość", - 'in' => "zawiera nieprawidłową wartość", - 'notIn' => "zawiera nieprawidłową wartość", - 'ip' => "nie jest prawidłowym adresem IP", - 'email' => "nie jest prawidłowym adresem email", - 'url' => "nie jest URL", - 'urlActive' => "musi być aktywną domeną", - 'alpha' => "musi zawierać tylko litery a-z", - 'alphaNum' => "musi zawierać tylko litery a-z i/lub cyfry 0-9", - 'slug' => "musi zawierać tylko litery a-z i/lub cyfry 0-9, myślinik I podkreślnik", - 'regex' => "zawiera nieprawidłowe znaki", - 'date' => "nie jest prawidłową datą", - 'dateFormat' => "Data musi być w formacie '%s'", - 'dateBefore' => "Data musi występować przed '%s'", - 'dateAfter' => "Data musi następować po '%s'", - 'contains' => "Musi zawierać %s", - 'boolean' => "musi być wartością logiczną", + 'required' => "jest wymagane", + 'equals' => "musi być takie same jak '%s'", + 'different' => "musi być różne od '%s'", + 'accepted' => "musi być zaakceptowane", + 'numeric' => "musi być liczbą", + 'integer' => "musi być liczbą całkowitą", + 'length' => "musi być dłuższe niż %d", + 'min' => "musi być przynajmniej %s", + 'max' => "nie może być większe niż %s", + 'listContains' => "zawiera nieprawidłową wartość", + 'in' => "zawiera nieprawidłową wartość", + 'notIn' => "zawiera nieprawidłową wartość", + 'ip' => "nie jest prawidłowym adresem IP", + 'email' => "nie jest prawidłowym adresem email", + 'url' => "nie jest URL", + 'urlActive' => "musi być aktywną domeną", + 'alpha' => "musi zawierać tylko litery a-z", + 'alphaNum' => "musi zawierać tylko litery a-z i/lub cyfry 0-9", + 'slug' => "musi zawierać tylko litery a-z i/lub cyfry 0-9, myślinik I podkreślnik", + 'regex' => "zawiera nieprawidłowe znaki", + 'date' => "nie jest prawidłową datą", + 'dateFormat' => "Data musi być w formacie '%s'", + 'dateBefore' => "Data musi występować przed '%s'", + 'dateAfter' => "Data musi następować po '%s'", + 'contains' => "Musi zawierać %s", + 'boolean' => "musi być wartością logiczną", 'lengthBetween' => "ilość znaków musi być między %d a %d", - 'creditCard' => "musi być prawidłowym numerem karty kredytowej", - "lengthMin" => "musi zawierać więcej niż %d znaków", - "lengthMax" => "musi zawierać mniej niż %d znaków", - "instanceOf" => "musi być instancją '%s'", + 'creditCard' => "musi być prawidłowym numerem karty kredytowej", + "lengthMin" => "musi zawierać więcej niż %d znaków", + "lengthMax" => "musi zawierać mniej niż %d znaków", + "instanceOf" => "musi być instancją '%s'", ); diff --git a/src/validator/lang/pt-br.php b/src/validator/lang/pt-br.php index e32afca..b7bc175 100644 --- a/src/validator/lang/pt-br.php +++ b/src/validator/lang/pt-br.php @@ -1,37 +1,37 @@ "é obrigatório", - 'equals' => "deve ser o mesmo que '%s'", - 'different' => "deve ser diferente de '%s'", - 'accepted' => "deve ser aceito", - 'numeric' => "deve ser um número", - 'integer' => "deve ser um inteiro", - 'length' => "deve ter %d caracteres", - 'min' => "deve ser maior que %s", - 'max' => "deve ser menor que %s", - 'in' => "contém um valor inválido", - 'notIn' => "contém um valor inválido", - 'ip' => "não é um IP válido", - 'email' => "não é um email válido", - 'url' => "não é uma URL válida", - 'urlActive' => "deve ser um domínio ativo", - 'alpha' => "deve conter as letras a-z", - 'alphaNum' => "deve conter apenas letras a-z e/ou números 0-9", - 'slug' => "deve conter apenas letras a-z, números 0-9, ou os caracteres - ou _", - 'regex' => "contém caracteres inválidos", - 'date' => "não é uma data válida", - 'dateFormat' => "deve ser uma data no formato '%s'", - 'dateBefore' => "deve ser uma data anterior a '%s'", - 'dateAfter' => "deve ser uma data posterior a '%s'", - 'contains' => "deve conter %s", - 'boolean' => "deve ser um booleano", - 'lengthBetween' => "deve estar entre %d e %d caracteres", - 'creditCard' => "deve ser um numero de cartão de credito válido", - 'lengthMin' => "deve ter ao menos %d caracteres", - 'lengthMax' => "não deve exceder %d caracteres", - 'instanceOf' => "deve ser uma instância de '%s'", + 'required' => "é obrigatório", + 'equals' => "deve ser o mesmo que '%s'", + 'different' => "deve ser diferente de '%s'", + 'accepted' => "deve ser aceito", + 'numeric' => "deve ser um número", + 'integer' => "deve ser um inteiro", + 'length' => "deve ter %d caracteres", + 'min' => "deve ser maior que %s", + 'max' => "deve ser menor que %s", + 'in' => "contém um valor inválido", + 'notIn' => "contém um valor inválido", + 'ip' => "não é um IP válido", + 'email' => "não é um email válido", + 'url' => "não é uma URL válida", + 'urlActive' => "deve ser um domínio ativo", + 'alpha' => "deve conter as letras a-z", + 'alphaNum' => "deve conter apenas letras a-z e/ou números 0-9", + 'slug' => "deve conter apenas letras a-z, números 0-9, ou os caracteres - ou _", + 'regex' => "contém caracteres inválidos", + 'date' => "não é uma data válida", + 'dateFormat' => "deve ser uma data no formato '%s'", + 'dateBefore' => "deve ser uma data anterior a '%s'", + 'dateAfter' => "deve ser uma data posterior a '%s'", + 'contains' => "deve conter %s", + 'boolean' => "deve ser um booleano", + 'lengthBetween' => "deve estar entre %d e %d caracteres", + 'creditCard' => "deve ser um numero de cartão de credito válido", + 'lengthMin' => "deve ter ao menos %d caracteres", + 'lengthMax' => "não deve exceder %d caracteres", + 'instanceOf' => "deve ser uma instância de '%s'", 'containsUnique' => "deve conter apenas valores únicos", - 'subset' => "contém um item que não está na lista", - 'arrayHasKeys' => "não contém todas as chaves requeridas" + 'subset' => "contém um item que não está na lista", + 'arrayHasKeys' => "não contém todas as chaves requeridas" ); \ No newline at end of file diff --git a/src/validator/lang/ro.php b/src/validator/lang/ro.php index 5efa2fa..ffa1608 100644 --- a/src/validator/lang/ro.php +++ b/src/validator/lang/ro.php @@ -1,35 +1,35 @@ "se cere", - 'equals' => "trebuie sa fie la fel ca '%s'", - 'different' => "trebuie sa fie diferit de '%s'", - 'accepted' => "trebuie sa fie acceptat", - 'numeric' => "trebuie sa fie numeric", - 'integer' => "trebuie sa fie intreg", - 'length' => "trebuie sa fie mai lung decat %d", - 'min' => "trebuie sa fie cel putin %s", - 'max' => "nu trebuie sa fie mai mult de %s", - 'listContains' => "contine caractere invalide", - 'in' => "contine caractere invalide", - 'notIn' => "contine o valoare invalida", - 'ip' => "nu este o adresa IP valida", - 'email' => "nu este o adresa de email valida", - 'url' => "nu este un URL", - 'urlActive' => "trebuie sa fie un domeniu activ", - 'alpha' => "trebuie sa contina doar litere de la a-z", - 'alphaNum' => "trebuie sa contina doar numere de la a-z si/sau numere 0-9", - 'slug' => "trebuie sa contina doar litere de la a-z, numere de la 0-9, cratime si underline '_'", - 'regex' => "contine caractere invalide", - 'date' => "nu este o data valida", - 'dateFormat' => "trebuie sa fie o data care sa aiba forma '%s'", - 'dateBefore' => "trebuie sa fie o data inainte de '%s'", - 'dateAfter' => "trebuie sa fie o data dupa '%s'", - 'contains' => "trebuie sa contina %s", - 'boolean' => "trebuie sa fie o constructie logica", + 'required' => "se cere", + 'equals' => "trebuie sa fie la fel ca '%s'", + 'different' => "trebuie sa fie diferit de '%s'", + 'accepted' => "trebuie sa fie acceptat", + 'numeric' => "trebuie sa fie numeric", + 'integer' => "trebuie sa fie intreg", + 'length' => "trebuie sa fie mai lung decat %d", + 'min' => "trebuie sa fie cel putin %s", + 'max' => "nu trebuie sa fie mai mult de %s", + 'listContains' => "contine caractere invalide", + 'in' => "contine caractere invalide", + 'notIn' => "contine o valoare invalida", + 'ip' => "nu este o adresa IP valida", + 'email' => "nu este o adresa de email valida", + 'url' => "nu este un URL", + 'urlActive' => "trebuie sa fie un domeniu activ", + 'alpha' => "trebuie sa contina doar litere de la a-z", + 'alphaNum' => "trebuie sa contina doar numere de la a-z si/sau numere 0-9", + 'slug' => "trebuie sa contina doar litere de la a-z, numere de la 0-9, cratime si underline '_'", + 'regex' => "contine caractere invalide", + 'date' => "nu este o data valida", + 'dateFormat' => "trebuie sa fie o data care sa aiba forma '%s'", + 'dateBefore' => "trebuie sa fie o data inainte de '%s'", + 'dateAfter' => "trebuie sa fie o data dupa '%s'", + 'contains' => "trebuie sa contina %s", + 'boolean' => "trebuie sa fie o constructie logica", 'lengthBetween' => "trebuie sa contina intre %d si %d caractere", - 'creditCard' => "trebuie sa fie nu numar de card de credit valid", - "lengthMin" => "trebuie sa contina caractere mai multe decat %d", - "lengthMax" => "trebuie sa contina mai putin de %d caractere", - "instanceOf" => "trebuie sa fie un exemplu de '%s’", + 'creditCard' => "trebuie sa fie nu numar de card de credit valid", + "lengthMin" => "trebuie sa contina caractere mai multe decat %d", + "lengthMax" => "trebuie sa contina mai putin de %d caractere", + "instanceOf" => "trebuie sa fie un exemplu de '%s’", ); diff --git a/src/validator/lang/ru.php b/src/validator/lang/ru.php index b934046..f383ac5 100644 --- a/src/validator/lang/ru.php +++ b/src/validator/lang/ru.php @@ -1,39 +1,39 @@ "обязательно для заполнения", - 'equals' => "должно совпадать со значением '%s'", - 'different' => "должно отличаться от '%s'", - 'accepted' => "должно быть указано", - 'numeric' => "должно содержать числовое значение", - 'integer' => "должно быть числом", - 'length' => "должно быть длиннее, чем %d", - 'min' => "должно быть не менее, чем %s", - 'max' => "должно быть не более, чем %s", - 'listContains' => "содержит неверное значение", - 'in' => "содержит неверное значение", - 'notIn' => "содержит неверное значение", - 'ip' => "не является валидным IP адресом", - 'ipv4' => "не является валидным IPv4 адресом", - 'ipv6' => "не является валидным IPv6 адресом", - 'email' => "не является валидным email адресом", - 'url' => "не является валидной ссылкой", - 'urlActive' => "содержит не активную ссылку", - 'alpha' => "должно содержать только латинские символы", - 'alphaNum' => "должно содержать только латинские символы и/или цифры", - 'slug' => "должно содержать только латинские символы, цифры, тире и подчёркивания", - 'regex' => "содержит недопустимые символы", - 'date' => "не является датой", - 'dateFormat' => "должно содержать дату следующего формата: %s", - 'dateBefore' => "должно содержать дату не позднее, чем %s", - 'dateAfter' => "должно содержать дату не ранее, чем %s", - 'contains' => "должно содержать %s", - 'boolean' => "должно содержать логическое значение", - 'lengthBetween' => "должно содержать от %d до %d символов", - 'creditCard' => "должно быть номером кредитной карты", - 'lengthMin' => "должно содержать более %d символов", - 'lengthMax' => "должно содержать менее %d символов", - 'instanceOf' => "должно быть объектом класса '%s'", + 'required' => "обязательно для заполнения", + 'equals' => "должно совпадать со значением '%s'", + 'different' => "должно отличаться от '%s'", + 'accepted' => "должно быть указано", + 'numeric' => "должно содержать числовое значение", + 'integer' => "должно быть числом", + 'length' => "должно быть длиннее, чем %d", + 'min' => "должно быть не менее, чем %s", + 'max' => "должно быть не более, чем %s", + 'listContains' => "содержит неверное значение", + 'in' => "содержит неверное значение", + 'notIn' => "содержит неверное значение", + 'ip' => "не является валидным IP адресом", + 'ipv4' => "не является валидным IPv4 адресом", + 'ipv6' => "не является валидным IPv6 адресом", + 'email' => "не является валидным email адресом", + 'url' => "не является валидной ссылкой", + 'urlActive' => "содержит не активную ссылку", + 'alpha' => "должно содержать только латинские символы", + 'alphaNum' => "должно содержать только латинские символы и/или цифры", + 'slug' => "должно содержать только латинские символы, цифры, тире и подчёркивания", + 'regex' => "содержит недопустимые символы", + 'date' => "не является датой", + 'dateFormat' => "должно содержать дату следующего формата: %s", + 'dateBefore' => "должно содержать дату не позднее, чем %s", + 'dateAfter' => "должно содержать дату не ранее, чем %s", + 'contains' => "должно содержать %s", + 'boolean' => "должно содержать логическое значение", + 'lengthBetween' => "должно содержать от %d до %d символов", + 'creditCard' => "должно быть номером кредитной карты", + 'lengthMin' => "должно содержать более %d символов", + 'lengthMax' => "должно содержать менее %d символов", + 'instanceOf' => "должно быть объектом класса '%s'", 'containsUnique' => "должно содержать только уникальные элементы", - 'subset' => "содержит элемент, не указанный в списке", + 'subset' => "содержит элемент, не указанный в списке", ); diff --git a/src/validator/lang/sk.php b/src/validator/lang/sk.php index 859e53e..29e7b9c 100644 --- a/src/validator/lang/sk.php +++ b/src/validator/lang/sk.php @@ -1,35 +1,35 @@ "je povinná položka", - 'equals' => "musí byť rovnaký ako '%s'", - 'different' => "musí byť rôzny od '%s'", - 'accepted' => "musí byť akceptovaný", - 'numeric' => "musí byť číslo", - 'integer' => "musí byť celé číslo", - 'length' => "musí byť dlhý aspoň %d", - 'min' => "musí byť dlhý minimálne %s", - 'max' => "musí byť maximálne %s", - 'listContains' => "obsahuje nepovolenú hodnotu", - 'in' => "obsahuje nepovolenú hodnotu", - 'notIn' => "obsahuje nepovolenú hodnotu", - 'ip' => "nie je korektná IP adresa", - 'email' => "nie je korektný e-mail", - 'url' => "nie je URL", - 'urlActive' => "musí byť aktívna URL", - 'alpha' => "musí obsahovať len písmená a-z", - 'alphaNum' => "musí obsahovať len písmená a-z a/alebo čísla 0-9", - 'slug' => "musí obsahovať len písmená a-z, čísla 0-9, pomlčky alebo podtržítka", - 'regex' => "obsahuje nepovolené znaky", - 'date' => "nie je korektný formáť", - 'dateFormat' => "musí byť dátum formátu '%s'", - 'dateBefore' => "musí byť dátum pred '%s'", - 'dateAfter' => "musí byť dátum po '%s'", - 'contains' => "musí obsahovať %s", - 'boolean' => "musí byť pravdivostná hodnota (boolean)", + 'required' => "je povinná položka", + 'equals' => "musí byť rovnaký ako '%s'", + 'different' => "musí byť rôzny od '%s'", + 'accepted' => "musí byť akceptovaný", + 'numeric' => "musí byť číslo", + 'integer' => "musí byť celé číslo", + 'length' => "musí byť dlhý aspoň %d", + 'min' => "musí byť dlhý minimálne %s", + 'max' => "musí byť maximálne %s", + 'listContains' => "obsahuje nepovolenú hodnotu", + 'in' => "obsahuje nepovolenú hodnotu", + 'notIn' => "obsahuje nepovolenú hodnotu", + 'ip' => "nie je korektná IP adresa", + 'email' => "nie je korektný e-mail", + 'url' => "nie je URL", + 'urlActive' => "musí byť aktívna URL", + 'alpha' => "musí obsahovať len písmená a-z", + 'alphaNum' => "musí obsahovať len písmená a-z a/alebo čísla 0-9", + 'slug' => "musí obsahovať len písmená a-z, čísla 0-9, pomlčky alebo podtržítka", + 'regex' => "obsahuje nepovolené znaky", + 'date' => "nie je korektný formáť", + 'dateFormat' => "musí byť dátum formátu '%s'", + 'dateBefore' => "musí byť dátum pred '%s'", + 'dateAfter' => "musí byť dátum po '%s'", + 'contains' => "musí obsahovať %s", + 'boolean' => "musí byť pravdivostná hodnota (boolean)", 'lengthBetween' => "musí byť %d až %d znakov dlhý", - 'creditCard' => "musí byť korektné číslo kreditnej karty", - "lengthMin" => "musí byť aspoň %d znakov dlhý", - "lengthMax" => "musí byť najviac %d znakov dlhý", - "instanceOf" => "musí byť inštanciou '%s'" + 'creditCard' => "musí byť korektné číslo kreditnej karty", + "lengthMin" => "musí byť aspoň %d znakov dlhý", + "lengthMax" => "musí byť najviac %d znakov dlhý", + "instanceOf" => "musí byť inštanciou '%s'" ); diff --git a/src/validator/lang/sl.php b/src/validator/lang/sl.php index ecc46dc..26b7549 100644 --- a/src/validator/lang/sl.php +++ b/src/validator/lang/sl.php @@ -1,42 +1,42 @@ "potrebno", - 'equals' => "mora biti enak '% s'", - 'different' => "mora biti drugačen od '% s'", - 'accepted' => "mora biti označeno", - 'numeric' => "mora biti številka", - 'integer' => "mora biti celo število", - 'length' => "ne sme biti daljši od% d", - 'min' => "mora biti večji od% s", - 'max' => "mora biti manjši od% s", - 'listContains' => "vsebuje neveljavno vrednost", - 'in' => "vsebuje neveljavno vrednost", - 'notIn' => "vsebuje neveljavno vrednost", - 'ip' => "ni veljaven naslov IP", - 'ipv4' => "ni veljaven naslov IPv4", - 'ipv6' => "ni veljaven naslov IPv6", - 'email' => "ni veljaven e-poštni naslov", - 'url' => "ni veljaven URL", - 'urlActive' => "mora biti aktivna domena", - 'alpha' => "mora vsebovati samo črke a-z", - 'alphaNum' => "mora vsebovati samo črke a-z in / ali številke 0-9", - 'slug' => "mora vsebovati samo črke a-z, številke 0-9, črtice in podčrtaje", - 'regex' => "vsebuje neveljavne znake", - 'date' => "ni veljaven datum", - 'dateFormat' => "mora biti datum s formatom '% s'", - 'dateBefore' => "mora biti datum pred '% s'", - 'dateAfter' => "mora biti datum za '% s'", - 'contains' => "mora vsebovati% s", - 'boolean' => "mora biti boolean", - 'lengthBetween' => "mora biti med% d in% d znaki", - 'creditCard' => "mora biti veljavna številka kreditne kartice", - 'lengthMin' => "mora biti dolg vsaj% d znakov", - 'lengthMax' => "ne sme presegati% d znakov", - 'instanceOf' => "mora biti primerek '% s'", + 'required' => "potrebno", + 'equals' => "mora biti enak '% s'", + 'different' => "mora biti drugačen od '% s'", + 'accepted' => "mora biti označeno", + 'numeric' => "mora biti številka", + 'integer' => "mora biti celo število", + 'length' => "ne sme biti daljši od% d", + 'min' => "mora biti večji od% s", + 'max' => "mora biti manjši od% s", + 'listContains' => "vsebuje neveljavno vrednost", + 'in' => "vsebuje neveljavno vrednost", + 'notIn' => "vsebuje neveljavno vrednost", + 'ip' => "ni veljaven naslov IP", + 'ipv4' => "ni veljaven naslov IPv4", + 'ipv6' => "ni veljaven naslov IPv6", + 'email' => "ni veljaven e-poštni naslov", + 'url' => "ni veljaven URL", + 'urlActive' => "mora biti aktivna domena", + 'alpha' => "mora vsebovati samo črke a-z", + 'alphaNum' => "mora vsebovati samo črke a-z in / ali številke 0-9", + 'slug' => "mora vsebovati samo črke a-z, številke 0-9, črtice in podčrtaje", + 'regex' => "vsebuje neveljavne znake", + 'date' => "ni veljaven datum", + 'dateFormat' => "mora biti datum s formatom '% s'", + 'dateBefore' => "mora biti datum pred '% s'", + 'dateAfter' => "mora biti datum za '% s'", + 'contains' => "mora vsebovati% s", + 'boolean' => "mora biti boolean", + 'lengthBetween' => "mora biti med% d in% d znaki", + 'creditCard' => "mora biti veljavna številka kreditne kartice", + 'lengthMin' => "mora biti dolg vsaj% d znakov", + 'lengthMax' => "ne sme presegati% d znakov", + 'instanceOf' => "mora biti primerek '% s'", 'containsUnique' => "mora vsebovati samo edinstvene elemente", - 'requiredWith' => "je potrebno", - 'requiredWithout'=> "je potrebno", - 'subset' => "vsebuje element, ki ga ni na seznamu", - 'arrayHasKeys' => "ne vsebuje vseh potrebnih tipk", + 'requiredWith' => "je potrebno", + 'requiredWithout' => "je potrebno", + 'subset' => "vsebuje element, ki ga ni na seznamu", + 'arrayHasKeys' => "ne vsebuje vseh potrebnih tipk", ); diff --git a/src/validator/lang/sv.php b/src/validator/lang/sv.php index 3cf04e3..e11e447 100644 --- a/src/validator/lang/sv.php +++ b/src/validator/lang/sv.php @@ -1,35 +1,35 @@ "är obligatorisk", - 'equals' => "måste vara samma som '%s'", - 'different' => "får inte vara samma som '%s'", - 'accepted' => "måste accepteras", - 'numeric' => "måste vara numerisk", - 'integer' => "måste vara ett heltal", - 'length' => "måste vara %d tecken långt", - 'min' => "måste vara minst %s", - 'max' => "får inte vara mer än %s", - 'listContains' => "innehåller ogiltigt värde", - 'in' => "innehåller ogiltigt värde", - 'notIn' => "innehåller ogiltigt värde", - 'ip' => "är inte en giltig IP-adress", - 'email' => "är inte en giltig e-postadress", - 'url' => "är inte en giltig URL", - 'urlActive' => "måste vara ett aktivt domännamn", - 'alpha' => "får bara innehålla bokstäver a-z", - 'alphaNum' => "får bara innehålla bokstäver a-z och/eller siffror 0-9", - 'slug' => "får bara innehålla bokstäver a-z och/eller siffror 0-9, bindesstreck och understreck", - 'regex' => "innehåller ogiltiga tecken", - 'date' => "är inte ett giltigt datum", - 'dateFormat' => "måste vara ett datum med formatet '%s'", - 'dateBefore' => "måste vara ett datum före '%s'", - 'dateAfter' => "måste vara ett datum efter '%s'", - 'contains' => "måste innehålla %s", - 'boolean' => "måste vara ett booleskt värde", - 'lengthBetween' => "måste vara mellan %d och %d tecken långt", - 'creditCard' => "måste vara ett giltigt kreditkortsnummer", - 'lengthMin' => "måste vara minst %d tecken långt", - 'lengthMax' => "får inte överstiga %d tecken", - 'instanceOf' => "måste vara en instans av '%s'" + 'required' => "är obligatorisk", + 'equals' => "måste vara samma som '%s'", + 'different' => "får inte vara samma som '%s'", + 'accepted' => "måste accepteras", + 'numeric' => "måste vara numerisk", + 'integer' => "måste vara ett heltal", + 'length' => "måste vara %d tecken långt", + 'min' => "måste vara minst %s", + 'max' => "får inte vara mer än %s", + 'listContains' => "innehåller ogiltigt värde", + 'in' => "innehåller ogiltigt värde", + 'notIn' => "innehåller ogiltigt värde", + 'ip' => "är inte en giltig IP-adress", + 'email' => "är inte en giltig e-postadress", + 'url' => "är inte en giltig URL", + 'urlActive' => "måste vara ett aktivt domännamn", + 'alpha' => "får bara innehålla bokstäver a-z", + 'alphaNum' => "får bara innehålla bokstäver a-z och/eller siffror 0-9", + 'slug' => "får bara innehålla bokstäver a-z och/eller siffror 0-9, bindesstreck och understreck", + 'regex' => "innehåller ogiltiga tecken", + 'date' => "är inte ett giltigt datum", + 'dateFormat' => "måste vara ett datum med formatet '%s'", + 'dateBefore' => "måste vara ett datum före '%s'", + 'dateAfter' => "måste vara ett datum efter '%s'", + 'contains' => "måste innehålla %s", + 'boolean' => "måste vara ett booleskt värde", + 'lengthBetween' => "måste vara mellan %d och %d tecken långt", + 'creditCard' => "måste vara ett giltigt kreditkortsnummer", + 'lengthMin' => "måste vara minst %d tecken långt", + 'lengthMax' => "får inte överstiga %d tecken", + 'instanceOf' => "måste vara en instans av '%s'" ); diff --git a/src/validator/lang/th.php b/src/validator/lang/th.php index 6f4af40..5343f23 100644 --- a/src/validator/lang/th.php +++ b/src/validator/lang/th.php @@ -1,35 +1,35 @@ "นั้นจำเป็นต้องมี", - 'equals' => "ต้องเหมือนกับ '%s'", - 'different' => "ต้องแตกต่างจาก '%s'", - 'accepted' => "ต้องถูกยอมรับ", - 'numeric' => "ต้องเป็นตัวเลข", - 'integer' => "ต้องเป็นตัวเลข integer", - 'length' => "ต้องมีความยาวมากกว่า %d", - 'min' => "ต้องมีอย่างน้อย %s", - 'max' => "ต้องไม่มากเกิน %s", - 'listContains' => "ประกอบด้วยค่าที่ไม่ถูกต้อง", - 'in' => "ประกอบด้วยค่าที่ไม่ถูกต้อง", - 'notIn' => "ประกอบด้วยค่าที่ไม่ถูกต้อง", - 'ip' => "ไม่ใช่ IP ที่ถูกต้อง", - 'email' => "ไม่ใช่อีเมลที่ถูกต้อง", - 'url' => "ไม่ใช่ลิงก์", - 'urlActive' => "ต้องไม่ใช่โดเมนที่ใช้งานอยู่", - 'alpha' => "ต้องมีแค่ตัวอักษร a-z", - 'alphaNum' => "ต้องมีแค่ตัวอักษร a-z และ/หรือ ตัวเลข 0-9", - 'slug' => "ต้องมีแค่ตัวอักษร a-z ตัวเลข 0-9 / และ _", - 'regex' => "มีตัวอักษรที่ไม่ถูกต้อง", - 'date' => "ไม่ใช่วันที่ที่ถูกต้อง", - 'dateFormat' => "ต้องเป็นวันที่ในรูปแบบ '%s'", - 'dateBefore' => "ต้องเป็นวันที่ก่อน '%s'", - 'dateAfter' => "ต้องเป็นวันที่หลัง '%s'", - 'contains' => "ต้องมี %s", - 'boolean' => "ต้องเป็น boolean", + 'required' => "นั้นจำเป็นต้องมี", + 'equals' => "ต้องเหมือนกับ '%s'", + 'different' => "ต้องแตกต่างจาก '%s'", + 'accepted' => "ต้องถูกยอมรับ", + 'numeric' => "ต้องเป็นตัวเลข", + 'integer' => "ต้องเป็นตัวเลข integer", + 'length' => "ต้องมีความยาวมากกว่า %d", + 'min' => "ต้องมีอย่างน้อย %s", + 'max' => "ต้องไม่มากเกิน %s", + 'listContains' => "ประกอบด้วยค่าที่ไม่ถูกต้อง", + 'in' => "ประกอบด้วยค่าที่ไม่ถูกต้อง", + 'notIn' => "ประกอบด้วยค่าที่ไม่ถูกต้อง", + 'ip' => "ไม่ใช่ IP ที่ถูกต้อง", + 'email' => "ไม่ใช่อีเมลที่ถูกต้อง", + 'url' => "ไม่ใช่ลิงก์", + 'urlActive' => "ต้องไม่ใช่โดเมนที่ใช้งานอยู่", + 'alpha' => "ต้องมีแค่ตัวอักษร a-z", + 'alphaNum' => "ต้องมีแค่ตัวอักษร a-z และ/หรือ ตัวเลข 0-9", + 'slug' => "ต้องมีแค่ตัวอักษร a-z ตัวเลข 0-9 / และ _", + 'regex' => "มีตัวอักษรที่ไม่ถูกต้อง", + 'date' => "ไม่ใช่วันที่ที่ถูกต้อง", + 'dateFormat' => "ต้องเป็นวันที่ในรูปแบบ '%s'", + 'dateBefore' => "ต้องเป็นวันที่ก่อน '%s'", + 'dateAfter' => "ต้องเป็นวันที่หลัง '%s'", + 'contains' => "ต้องมี %s", + 'boolean' => "ต้องเป็น boolean", 'lengthBetween' => "ต้องอยู่ระหว่าง %d ถึง %d ตัวอักษร", - 'creditCard' => "ต้องเป็นหมายเลขบัตรเครดิตที่ถูกต้อง", - "lengthMin" => "ต้องมีมากกว่า %d ตัวอักษร", - "lengthMax" => "ต้องมีน้อยกว่า %d ตัวอักษร", - "instanceOf" => "ต้องเป็นส่วนหนึ่งของ '%s'" + 'creditCard' => "ต้องเป็นหมายเลขบัตรเครดิตที่ถูกต้อง", + "lengthMin" => "ต้องมีมากกว่า %d ตัวอักษร", + "lengthMax" => "ต้องมีน้อยกว่า %d ตัวอักษร", + "instanceOf" => "ต้องเป็นส่วนหนึ่งของ '%s'" ); diff --git a/src/validator/lang/tr.php b/src/validator/lang/tr.php index 0c4b26f..022eb3e 100644 --- a/src/validator/lang/tr.php +++ b/src/validator/lang/tr.php @@ -1,35 +1,35 @@ "gerekli ", - 'equals' => "bununla aynı olmalı '%s'", - 'different' => "bundan değişik olmalı '%s'", - 'accepted' => "kabul edilebilir olmalı", - 'numeric' => "numerik olmalı", - 'integer' => "sayı olmalı", - 'length' => "en az %d adet uzunluğunda olmalı", - 'min' => "en az böyle olmalı %s", - 'max' => "bundan daha fazla olmalı %s", - 'listContains' => "geçersiz değer içeriyor", - 'in' => "geçersiz değer içeriyor", - 'notIn' => "geçersiz değer içeriyor", - 'ip' => "geçerli bir IP adresi değil", - 'email' => "geçerli bir eposta adresi değil", - 'url' => "bir URL değil", - 'urlActive' => "aktif bir alan adı olmalı", - 'alpha' => "sadece harf içermeli a-z", - 'alphaNum' => "sadece harf (a-z) ve/veya sayılar (0-9) içermeli", - 'slug' => "sadece harf (a-z), numbers sayılar (0-9), tire ve alt tire içermeli", - 'regex' => "geçersiz karakterler içeriyor", - 'date' => "geçerli bir karakter değil", - 'dateFormat' => "bu biçimde bir tarih olmalı '%s'", - 'dateBefore' => "bu tarihden önce olmalı '%s'", - 'dateAfter' => "bu tarihden sonra olmalı '%s'", - 'contains' => "bunu içermeli %s", - 'boolean' => "boolean olmalı", + 'required' => "gerekli ", + 'equals' => "bununla aynı olmalı '%s'", + 'different' => "bundan değişik olmalı '%s'", + 'accepted' => "kabul edilebilir olmalı", + 'numeric' => "numerik olmalı", + 'integer' => "sayı olmalı", + 'length' => "en az %d adet uzunluğunda olmalı", + 'min' => "en az böyle olmalı %s", + 'max' => "bundan daha fazla olmalı %s", + 'listContains' => "geçersiz değer içeriyor", + 'in' => "geçersiz değer içeriyor", + 'notIn' => "geçersiz değer içeriyor", + 'ip' => "geçerli bir IP adresi değil", + 'email' => "geçerli bir eposta adresi değil", + 'url' => "bir URL değil", + 'urlActive' => "aktif bir alan adı olmalı", + 'alpha' => "sadece harf içermeli a-z", + 'alphaNum' => "sadece harf (a-z) ve/veya sayılar (0-9) içermeli", + 'slug' => "sadece harf (a-z), numbers sayılar (0-9), tire ve alt tire içermeli", + 'regex' => "geçersiz karakterler içeriyor", + 'date' => "geçerli bir karakter değil", + 'dateFormat' => "bu biçimde bir tarih olmalı '%s'", + 'dateBefore' => "bu tarihden önce olmalı '%s'", + 'dateAfter' => "bu tarihden sonra olmalı '%s'", + 'contains' => "bunu içermeli %s", + 'boolean' => "boolean olmalı", 'lengthBetween' => "%d ve %d karakter arasında olmalı", - 'creditCard' => "geçerli bir kredi kartı numarası olmalı", - "lengthMin" => "%d karakterden fazla içermeli", - "lengthMax" => "%d karakterden az içermeli", - "instanceOf" => "bunun bir örneği olmalı '%s'" + 'creditCard' => "geçerli bir kredi kartı numarası olmalı", + "lengthMin" => "%d karakterden fazla içermeli", + "lengthMax" => "%d karakterden az içermeli", + "instanceOf" => "bunun bir örneği olmalı '%s'" ); diff --git a/src/validator/lang/uk.php b/src/validator/lang/uk.php index 65df219..2671a69 100644 --- a/src/validator/lang/uk.php +++ b/src/validator/lang/uk.php @@ -1,34 +1,34 @@ "обов'язкове для заповнення", - 'equals' => "має містити '%s'", - 'different' => "має відрізнятися від '%s'", - 'accepted' => "має бути вказаним", - 'numeric' => "має містити числове значення", - 'integer' => "має бути числом", - 'length' => "має бути довшим, ніж %d", - 'min' => "має бути більше, ніж %s", - 'max' => "повинно бути менше, ніж %s", - 'listContains' => "містить невірне значення", - 'in' => "містить невірне значення", - 'notIn' => "містить невірне значення", - 'ip' => "не є валідною IP адресою", - 'email' => "не є валідною email адресою", - 'url' => "не є посиланням", - 'urlActive' => "містить не активне посилання", - 'alpha' => "повинно містити тільки латинські символи", - 'alphaNum' => "повинно містити тільки латинські символи та/або цифри", - 'slug' => "повинно містити тільки латинські символи, цифри, тире і підкреслення", - 'regex' => "містить неприпустимі символи", - 'date' => "не є датою", - 'dateFormat' => "має містити дату наступного формату:%s", - 'dateBefore' => "має містити дату не пізнішу, ніж %s", - 'dateAfter' => "має містити дату не ранішу, ніж %s", - 'contains' => "має містити %s", - 'boolean' => "має містити логічне значення", + 'required' => "обов'язкове для заповнення", + 'equals' => "має містити '%s'", + 'different' => "має відрізнятися від '%s'", + 'accepted' => "має бути вказаним", + 'numeric' => "має містити числове значення", + 'integer' => "має бути числом", + 'length' => "має бути довшим, ніж %d", + 'min' => "має бути більше, ніж %s", + 'max' => "повинно бути менше, ніж %s", + 'listContains' => "містить невірне значення", + 'in' => "містить невірне значення", + 'notIn' => "містить невірне значення", + 'ip' => "не є валідною IP адресою", + 'email' => "не є валідною email адресою", + 'url' => "не є посиланням", + 'urlActive' => "містить не активне посилання", + 'alpha' => "повинно містити тільки латинські символи", + 'alphaNum' => "повинно містити тільки латинські символи та/або цифри", + 'slug' => "повинно містити тільки латинські символи, цифри, тире і підкреслення", + 'regex' => "містить неприпустимі символи", + 'date' => "не є датою", + 'dateFormat' => "має містити дату наступного формату:%s", + 'dateBefore' => "має містити дату не пізнішу, ніж %s", + 'dateAfter' => "має містити дату не ранішу, ніж %s", + 'contains' => "має містити %s", + 'boolean' => "має містити логічне значення", 'lengthBetween' => "має містити від %d в до %d символів", - 'creditCard' => "має бути номером кредитної картки", - "lengthMin" => "має містити більше %d символів", - "lengthMax" => "має містити менше %d символів" + 'creditCard' => "має бути номером кредитної картки", + "lengthMin" => "має містити більше %d символів", + "lengthMax" => "має містити менше %d символів" ); diff --git a/src/validator/lang/vi.php b/src/validator/lang/vi.php index de7d91d..c465cb3 100644 --- a/src/validator/lang/vi.php +++ b/src/validator/lang/vi.php @@ -1,35 +1,35 @@ "là bắt buộc", - 'equals' => "phải giống '%s'", - 'different' => "phải khác '%s'", - 'accepted' => "được chấp nhận", - 'numeric' => "phải là số", - 'integer' => "phải là số nguyên", - 'length' => "phải dài hơn %d", - 'min' => "ít nhất %s", - 'max' => "tối đa %s", - 'listContains' => "chứa giá trị không hợp lệ", - 'in' => "chứa giá trị không hợp lệ", - 'notIn' => "chứa giá trị không hợp lệ", - 'ip' => "địa chỉ IP không hợp lệ", - 'email' => "địa chỉ email không hợp lệ", - 'url' => "không phải là URL", - 'urlActive' => "Domain chưa được kích hoạt", - 'alpha' => "chỉ chứa các kí tự a-z", - 'alphaNum' => "chỉ chứa các kí tự a-z hoặc số 0-9", - 'slug' => "chỉ chứa các kí tự a-z, số 0-9, gạch nối và gạch dưới", - 'regex' => "chứa kí tự không hợp lệ", - 'date' => "thời gian hợp lệ", - 'dateFormat' => "thời gian nên được định dạng '%s'", - 'dateBefore' => "thời gian nên trước '%s'", - 'dateAfter' => "thời gian nên sau '%s'", - 'contains' => "phải chứa %s", - 'boolean' => "phải là boolean", + 'required' => "là bắt buộc", + 'equals' => "phải giống '%s'", + 'different' => "phải khác '%s'", + 'accepted' => "được chấp nhận", + 'numeric' => "phải là số", + 'integer' => "phải là số nguyên", + 'length' => "phải dài hơn %d", + 'min' => "ít nhất %s", + 'max' => "tối đa %s", + 'listContains' => "chứa giá trị không hợp lệ", + 'in' => "chứa giá trị không hợp lệ", + 'notIn' => "chứa giá trị không hợp lệ", + 'ip' => "địa chỉ IP không hợp lệ", + 'email' => "địa chỉ email không hợp lệ", + 'url' => "không phải là URL", + 'urlActive' => "Domain chưa được kích hoạt", + 'alpha' => "chỉ chứa các kí tự a-z", + 'alphaNum' => "chỉ chứa các kí tự a-z hoặc số 0-9", + 'slug' => "chỉ chứa các kí tự a-z, số 0-9, gạch nối và gạch dưới", + 'regex' => "chứa kí tự không hợp lệ", + 'date' => "thời gian hợp lệ", + 'dateFormat' => "thời gian nên được định dạng '%s'", + 'dateBefore' => "thời gian nên trước '%s'", + 'dateAfter' => "thời gian nên sau '%s'", + 'contains' => "phải chứa %s", + 'boolean' => "phải là boolean", 'lengthBetween' => "phải từ %d đến %d kí tự", - 'creditCard' => "credit card không hợp lệ", - "lengthMin" => "ít nhất %d kí tự", - "lengthMax" => "tối đa %d kí tự", - "instanceOf" => "phải là instance của '%s'" + 'creditCard' => "credit card không hợp lệ", + "lengthMin" => "ít nhất %d kí tự", + "lengthMax" => "tối đa %d kí tự", + "instanceOf" => "phải là instance của '%s'" ); diff --git a/src/validator/lang/zh-cn.php b/src/validator/lang/zh-cn.php index 09bd637..052e830 100644 --- a/src/validator/lang/zh-cn.php +++ b/src/validator/lang/zh-cn.php @@ -1,40 +1,40 @@ "不能为空", - 'equals' => "必须和 '%s' 一致", - 'different' => "必须和 '%s' 不一致", - 'accepted' => "必须接受", - 'numeric' => "只能是数字", - 'integer' => "只能是整数", - 'length' => "长度必须等于 %d", - 'min' => "必须大于 %s", - 'max' => "必须小于 %s", - 'listContains' => "无效的值", - 'in' => "无效的值", - 'notIn' => "无效的值", - 'ip' => "无效IP地址", - 'email' => "无效邮箱地址", - 'url' => "无效的URL", - 'urlActive' => "必须是可用的域名", - 'alpha' => "只能包括英文字母(a-z)", - 'alphaNum' => "只能包括英文字母(a-z)和数字(0-9)", - 'slug' => "只能包括英文字母(a-z)、数字(0-9)、破折号和下划线", - 'regex' => "无效格式", - 'date' => "无效的日期", - 'dateFormat' => "日期的格式应该为 '%s'", - 'dateBefore' => "日期必须在 '%s' 之前", - 'dateAfter' => "日期必须在 '%s' 之后", - 'contains' => "必须包含 %s", - 'boolean' => "必须是真或假", + 'required' => "不能为空", + 'equals' => "必须和 '%s' 一致", + 'different' => "必须和 '%s' 不一致", + 'accepted' => "必须接受", + 'numeric' => "只能是数字", + 'integer' => "只能是整数", + 'length' => "长度必须等于 %d", + 'min' => "必须大于 %s", + 'max' => "必须小于 %s", + 'listContains' => "无效的值", + 'in' => "无效的值", + 'notIn' => "无效的值", + 'ip' => "无效IP地址", + 'email' => "无效邮箱地址", + 'url' => "无效的URL", + 'urlActive' => "必须是可用的域名", + 'alpha' => "只能包括英文字母(a-z)", + 'alphaNum' => "只能包括英文字母(a-z)和数字(0-9)", + 'slug' => "只能包括英文字母(a-z)、数字(0-9)、破折号和下划线", + 'regex' => "无效格式", + 'date' => "无效的日期", + 'dateFormat' => "日期的格式应该为 '%s'", + 'dateBefore' => "日期必须在 '%s' 之前", + 'dateAfter' => "日期必须在 '%s' 之后", + 'contains' => "必须包含 %s", + 'boolean' => "必须是真或假", 'lengthBetween' => "长度只能介于 %d 和 %d 之间", - 'creditCard' => "信用卡号码不正确", - 'lengthMin' => "长度必须大于 %d", - 'lengthMax' => "长度必须小于 %d", - 'instanceOf' => "必须是 '%s' 的实例", + 'creditCard' => "信用卡号码不正确", + 'lengthMin' => "长度必须大于 %d", + 'lengthMax' => "长度必须小于 %d", + 'instanceOf' => "必须是 '%s' 的实例", 'containsUnique' => "必须仅包含唯一的元素", - 'requiredWith' => "是必须的", + 'requiredWith' => "是必须的", 'requiredWithout' => "是必须的", - 'subset' => "包含不在列表中的项目", - 'arrayHasKeys' => "不包含所有必需的键", + 'subset' => "包含不在列表中的项目", + 'arrayHasKeys' => "不包含所有必需的键", ); diff --git a/src/validator/lang/zh-tw.php b/src/validator/lang/zh-tw.php index cf8d8b8..81258ce 100644 --- a/src/validator/lang/zh-tw.php +++ b/src/validator/lang/zh-tw.php @@ -1,40 +1,40 @@ "不能為空", - 'equals' => "必須和 '%s' 一致", - 'different' => "必須和 '%s' 不一致", - 'accepted' => "必須接受", - 'numeric' => "只能是數字", - 'integer' => "只能是整數", - 'length' => "長度必須大於 %d", - 'min' => "必須大於 %s", - 'max' => "必須小於 %s", - 'listContains' => "無效的值", - 'in' => "無效的值", - 'notIn' => "無效的值", - 'ip' => "無效IP地址", - 'email' => "無效郵箱地址", - 'url' => "無效的URL", - 'urlActive' => "必須是可用的域名", - 'alpha' => "只能包括英文字母(a-z)", - 'alphaNum' => "只能包括英文字母(a-z)和數字(0-9)", - 'slug' => "只能包括英文字母(a-z)、數字(0-9)、破折號和下劃線", - 'regex' => "無效格式", - 'date' => "無效的日期", - 'dateFormat' => "日期的格式應該為 '%s'", - 'dateBefore' => "日期必須在 '%s' 之前", - 'dateAfter' => "日期必須在 '%s' 之後", - 'contains' => "必須包含 %s", - 'boolean' => "必須是真或假", - 'lengthBetween' => "長度只能介於 %d 和 %d 之間", - 'creditCard' => "信用卡號碼不正確", - 'lengthMin' => "長度必須大於 %d", - 'lengthMax' => "長度必須小於 %d", - 'instanceOf' => "必須是 '%s' 的實例", - 'containsUnique' => "必須僅包含唯一的元素", - 'requiredWith' => "是必須的", - 'requiredWithout' => "是必須的", - 'subset' => "包含不在列表中的項目", - 'arrayHasKeys' => "不包含所有必需的鍵", + 'required' => "不能為空", + 'equals' => "必須和 '%s' 一致", + 'different' => "必須和 '%s' 不一致", + 'accepted' => "必須接受", + 'numeric' => "只能是數字", + 'integer' => "只能是整數", + 'length' => "長度必須大於 %d", + 'min' => "必須大於 %s", + 'max' => "必須小於 %s", + 'listContains' => "無效的值", + 'in' => "無效的值", + 'notIn' => "無效的值", + 'ip' => "無效IP地址", + 'email' => "無效郵箱地址", + 'url' => "無效的URL", + 'urlActive' => "必須是可用的域名", + 'alpha' => "只能包括英文字母(a-z)", + 'alphaNum' => "只能包括英文字母(a-z)和數字(0-9)", + 'slug' => "只能包括英文字母(a-z)、數字(0-9)、破折號和下劃線", + 'regex' => "無效格式", + 'date' => "無效的日期", + 'dateFormat' => "日期的格式應該為 '%s'", + 'dateBefore' => "日期必須在 '%s' 之前", + 'dateAfter' => "日期必須在 '%s' 之後", + 'contains' => "必須包含 %s", + 'boolean' => "必須是真或假", + 'lengthBetween' => "長度只能介於 %d 和 %d 之間", + 'creditCard' => "信用卡號碼不正確", + 'lengthMin' => "長度必須大於 %d", + 'lengthMax' => "長度必須小於 %d", + 'instanceOf' => "必須是 '%s' 的實例", + 'containsUnique' => "必須僅包含唯一的元素", + 'requiredWith' => "是必須的", + 'requiredWithout' => "是必須的", + 'subset' => "包含不在列表中的項目", + 'arrayHasKeys' => "不包含所有必需的鍵", );