From cb3c8aaf2d668d541568120f040b3a213fc18bc2 Mon Sep 17 00:00:00 2001 From: Skylar Ittner Date: Tue, 4 Dec 2018 19:46:08 -0700 Subject: [PATCH 1/9] Support undefined messages --- app.php | 50 ++++++++++++++++++++++++++++---------------------- 1 file changed, 28 insertions(+), 22 deletions(-) diff --git a/app.php b/app.php index 5cfcc36..12ece2f 100644 --- a/app.php +++ b/app.php @@ -1,5 +1,4 @@ ; rel=preload; as=script", fals get(MESSAGES[$_GET['msg']]['string'], false); + if (!empty($_GET['msg'])) { + if (array_key_exists($_GET['msg'], MESSAGES)) { + // optional string generation argument + if (!isset($_GET['arg']) || is_empty($_GET['arg'])) { + $alertmsg = $Strings->get(MESSAGES[$_GET['msg']]['string'], false); + } else { + $alertmsg = $Strings->build(MESSAGES[$_GET['msg']]['string'], ["arg" => strip_tags($_GET['arg'])], false); + } + $alerttype = MESSAGES[$_GET['msg']]['type']; + $alerticon = "square-o"; + switch (MESSAGES[$_GET['msg']]['type']) { + case "danger": + $alerticon = "times"; + break; + case "warning": + $alerticon = "exclamation-triangle"; + break; + case "info": + $alerticon = "info-circle"; + break; + case "success": + $alerticon = "check"; + break; + } } else { - $alertmsg = $Strings->build(MESSAGES[$_GET['msg']]['string'], ["arg" => strip_tags($_GET['arg'])], false); - } - $alerttype = MESSAGES[$_GET['msg']]['type']; - $alerticon = "square-o"; - switch (MESSAGES[$_GET['msg']]['type']) { - case "danger": - $alerticon = "times"; - break; - case "warning": - $alerticon = "exclamation-triangle"; - break; - case "info": - $alerticon = "info-circle"; - break; - case "success": - $alerticon = "check"; - break; + // We don't have a message for this, so just assume an error and escape stuff. + $alertmsg = htmlentities($Strings->get($_GET['msg'], false)); + $alerticon = "times"; + $alerttype = "danger"; } echo << From 4f1b81ff4bfd044e226f8803f590dda2d27df90a Mon Sep 17 00:00:00 2001 From: Skylar Ittner Date: Tue, 4 Dec 2018 19:48:23 -0700 Subject: [PATCH 2/9] Deprecate is_empty() --- app.php | 4 ++-- index.php | 2 +- mobile/index.php | 2 +- required.php | 1 + 4 files changed, 5 insertions(+), 4 deletions(-) diff --git a/app.php b/app.php index 12ece2f..b74d422 100644 --- a/app.php +++ b/app.php @@ -13,7 +13,7 @@ if ($_SESSION['loggedin'] != true) { require_once __DIR__ . "/pages.php"; $pageid = "home"; -if (isset($_GET['page']) && !is_empty($_GET['page'])) { +if (!empty($_GET['page'])) { $pg = strtolower($_GET['page']); $pg = preg_replace('/[^0-9a-z_]/', "", $pg); if (array_key_exists($pg, PAGES) && file_exists(__DIR__ . "/pages/" . $pg . ".php")) { @@ -68,7 +68,7 @@ header("Link: ; rel=preload; as=script", fals if (!empty($_GET['msg'])) { if (array_key_exists($_GET['msg'], MESSAGES)) { // optional string generation argument - if (!isset($_GET['arg']) || is_empty($_GET['arg'])) { + if (empty($_GET['arg'])) { $alertmsg = $Strings->get(MESSAGES[$_GET['msg']]['string'], false); } else { $alertmsg = $Strings->build(MESSAGES[$_GET['msg']]['string'], ["arg" => strip_tags($_GET['arg'])], false); diff --git a/index.php b/index.php index 3c992b3..1f8f76f 100644 --- a/index.php +++ b/index.php @@ -47,7 +47,7 @@ if (Login::checkLoginServer()) { $username_ok = true; break; default: - if (!is_empty($error)) { + if (!empty($error)) { $alert = $error; } else { $alert = $Strings->get("login error", false); diff --git a/mobile/index.php b/mobile/index.php index 5cc4575..de36d52 100644 --- a/mobile/index.php +++ b/mobile/index.php @@ -75,7 +75,7 @@ if (mobile_enabled() !== TRUE) { } // Make sure we have a username and access key -if (is_empty($VARS['username']) || is_empty($VARS['key'])) { +if (empty($VARS['username']) || empty($VARS['key'])) { http_response_code(401); die(json_encode(["status" => "ERROR", "msg" => "Missing username and/or access key."])); } diff --git a/required.php b/required.php index c296dcb..c67229f 100644 --- a/required.php +++ b/required.php @@ -133,6 +133,7 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') { } /** + * @deprecated * Checks if a string or whatever is empty. * @param $str The thingy to check * @return boolean True if it's empty or whatever. From 32cd18933dd316354da57c8d76dc66d424a2b8fb Mon Sep 17 00:00:00 2001 From: Skylar Ittner Date: Tue, 11 Dec 2018 21:39:25 -0700 Subject: [PATCH 3/9] Update FontAwesome from 5.3.1 to 5.6.0 --- static/css/svg-with-js.min.css | 4 ++-- static/js/fontawesome-all.min.js | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/static/css/svg-with-js.min.css b/static/css/svg-with-js.min.css index d303435..21ad29b 100644 --- a/static/css/svg-with-js.min.css +++ b/static/css/svg-with-js.min.css @@ -1,5 +1,5 @@ /*! - * Font Awesome Free 5.3.1 by @fontawesome - https://fontawesome.com + * Font Awesome Free 5.6.0 by @fontawesome - https://fontawesome.com * License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) */ -.svg-inline--fa,svg:not(:root).svg-inline--fa{overflow:visible}.svg-inline--fa{display:inline-block;font-size:inherit;height:1em;vertical-align:-.125em}.svg-inline--fa.fa-lg{vertical-align:-.225em}.svg-inline--fa.fa-w-1{width:.0625em}.svg-inline--fa.fa-w-2{width:.125em}.svg-inline--fa.fa-w-3{width:.1875em}.svg-inline--fa.fa-w-4{width:.25em}.svg-inline--fa.fa-w-5{width:.3125em}.svg-inline--fa.fa-w-6{width:.375em}.svg-inline--fa.fa-w-7{width:.4375em}.svg-inline--fa.fa-w-8{width:.5em}.svg-inline--fa.fa-w-9{width:.5625em}.svg-inline--fa.fa-w-10{width:.625em}.svg-inline--fa.fa-w-11{width:.6875em}.svg-inline--fa.fa-w-12{width:.75em}.svg-inline--fa.fa-w-13{width:.8125em}.svg-inline--fa.fa-w-14{width:.875em}.svg-inline--fa.fa-w-15{width:.9375em}.svg-inline--fa.fa-w-16{width:1em}.svg-inline--fa.fa-w-17{width:1.0625em}.svg-inline--fa.fa-w-18{width:1.125em}.svg-inline--fa.fa-w-19{width:1.1875em}.svg-inline--fa.fa-w-20{width:1.25em}.svg-inline--fa.fa-pull-left{margin-right:.3em;width:auto}.svg-inline--fa.fa-pull-right{margin-left:.3em;width:auto}.svg-inline--fa.fa-border{height:1.5em}.svg-inline--fa.fa-li{width:2em}.svg-inline--fa.fa-fw{width:1.25em}.fa-layers svg.svg-inline--fa{bottom:0;left:0;margin:auto;position:absolute;right:0;top:0}.fa-layers{display:inline-block;height:1em;position:relative;text-align:center;vertical-align:-.125em;width:1em}.fa-layers svg.svg-inline--fa{transform-origin:center center}.fa-layers-counter,.fa-layers-text{display:inline-block;position:absolute;text-align:center}.fa-layers-text{left:50%;top:50%;transform:translate(-50%,-50%);transform-origin:center center}.fa-layers-counter{background-color:#ff253a;border-radius:1em;box-sizing:border-box;color:#fff;height:1.5em;line-height:1;max-width:5em;min-width:1.5em;overflow:hidden;padding:.25em;right:0;text-overflow:ellipsis;top:0;transform:scale(.25);transform-origin:top right}.fa-layers-bottom-right{bottom:0;right:0;top:auto;transform:scale(.25);transform-origin:bottom right}.fa-layers-bottom-left{bottom:0;left:0;right:auto;top:auto;transform:scale(.25);transform-origin:bottom left}.fa-layers-top-right{right:0;top:0;transform:scale(.25);transform-origin:top right}.fa-layers-top-left{left:0;right:auto;top:0;transform:scale(.25);transform-origin:top left}.fa-lg{font-size:1.33333em;line-height:.75em;vertical-align:-.0667em}.fa-xs{font-size:.75em}.fa-sm{font-size:.875em}.fa-1x{font-size:1em}.fa-2x{font-size:2em}.fa-3x{font-size:3em}.fa-4x{font-size:4em}.fa-5x{font-size:5em}.fa-6x{font-size:6em}.fa-7x{font-size:7em}.fa-8x{font-size:8em}.fa-9x{font-size:9em}.fa-10x{font-size:10em}.fa-fw{text-align:center;width:1.25em}.fa-ul{list-style-type:none;margin-left:2.5em;padding-left:0}.fa-ul>li{position:relative}.fa-li{left:-2em;position:absolute;text-align:center;width:2em;line-height:inherit}.fa-border{border:.08em solid #eee;border-radius:.1em;padding:.2em .25em .15em}.fa-pull-left{float:left}.fa-pull-right{float:right}.fa.fa-pull-left,.fab.fa-pull-left,.fal.fa-pull-left,.far.fa-pull-left,.fas.fa-pull-left{margin-right:.3em}.fa.fa-pull-right,.fab.fa-pull-right,.fal.fa-pull-right,.far.fa-pull-right,.fas.fa-pull-right{margin-left:.3em}.fa-spin{animation:fa-spin 2s infinite linear}.fa-pulse{animation:fa-spin 1s infinite steps(8)}@keyframes fa-spin{0%{transform:rotate(0deg)}to{transform:rotate(1turn)}}.fa-rotate-90{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=1)";transform:rotate(90deg)}.fa-rotate-180{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=2)";transform:rotate(180deg)}.fa-rotate-270{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=3)";transform:rotate(270deg)}.fa-flip-horizontal{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=0, mirror=1)";transform:scaleX(-1)}.fa-flip-vertical{transform:scaleY(-1)}.fa-flip-horizontal.fa-flip-vertical,.fa-flip-vertical{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=2, mirror=1)"}.fa-flip-horizontal.fa-flip-vertical{transform:scale(-1)}:root .fa-flip-horizontal,:root .fa-flip-vertical,:root .fa-rotate-90,:root .fa-rotate-180,:root .fa-rotate-270{-webkit-filter:none;filter:none}.fa-stack{display:inline-block;height:2em;position:relative;width:2em}.fa-stack-1x,.fa-stack-2x{bottom:0;left:0;margin:auto;position:absolute;right:0;top:0}.svg-inline--fa.fa-stack-1x{height:1em;width:1em}.svg-inline--fa.fa-stack-2x{height:2em;width:2em}.fa-inverse{color:#fff}.sr-only{border:0;clip:rect(0,0,0,0);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px}.sr-only-focusable:active,.sr-only-focusable:focus{clip:auto;height:auto;margin:0;overflow:visible;position:static;width:auto} \ No newline at end of file +.svg-inline--fa,svg:not(:root).svg-inline--fa{overflow:visible}.svg-inline--fa{display:inline-block;font-size:inherit;height:1em;vertical-align:-.125em}.svg-inline--fa.fa-lg{vertical-align:-.225em}.svg-inline--fa.fa-w-1{width:.0625em}.svg-inline--fa.fa-w-2{width:.125em}.svg-inline--fa.fa-w-3{width:.1875em}.svg-inline--fa.fa-w-4{width:.25em}.svg-inline--fa.fa-w-5{width:.3125em}.svg-inline--fa.fa-w-6{width:.375em}.svg-inline--fa.fa-w-7{width:.4375em}.svg-inline--fa.fa-w-8{width:.5em}.svg-inline--fa.fa-w-9{width:.5625em}.svg-inline--fa.fa-w-10{width:.625em}.svg-inline--fa.fa-w-11{width:.6875em}.svg-inline--fa.fa-w-12{width:.75em}.svg-inline--fa.fa-w-13{width:.8125em}.svg-inline--fa.fa-w-14{width:.875em}.svg-inline--fa.fa-w-15{width:.9375em}.svg-inline--fa.fa-w-16{width:1em}.svg-inline--fa.fa-w-17{width:1.0625em}.svg-inline--fa.fa-w-18{width:1.125em}.svg-inline--fa.fa-w-19{width:1.1875em}.svg-inline--fa.fa-w-20{width:1.25em}.svg-inline--fa.fa-pull-left{margin-right:.3em;width:auto}.svg-inline--fa.fa-pull-right{margin-left:.3em;width:auto}.svg-inline--fa.fa-border{height:1.5em}.svg-inline--fa.fa-li{width:2em}.svg-inline--fa.fa-fw{width:1.25em}.fa-layers svg.svg-inline--fa{bottom:0;left:0;margin:auto;position:absolute;right:0;top:0}.fa-layers{display:inline-block;height:1em;position:relative;text-align:center;vertical-align:-.125em;width:1em}.fa-layers svg.svg-inline--fa{transform-origin:center center}.fa-layers-counter,.fa-layers-text{display:inline-block;position:absolute;text-align:center}.fa-layers-text{left:50%;top:50%;transform:translate(-50%,-50%);transform-origin:center center}.fa-layers-counter{background-color:#ff253a;border-radius:1em;box-sizing:border-box;color:#fff;height:1.5em;line-height:1;max-width:5em;min-width:1.5em;overflow:hidden;padding:.25em;right:0;text-overflow:ellipsis;top:0;transform:scale(.25);transform-origin:top right}.fa-layers-bottom-right{bottom:0;right:0;top:auto;transform:scale(.25);transform-origin:bottom right}.fa-layers-bottom-left{bottom:0;left:0;right:auto;top:auto;transform:scale(.25);transform-origin:bottom left}.fa-layers-top-right{right:0;top:0;transform:scale(.25);transform-origin:top right}.fa-layers-top-left{left:0;right:auto;top:0;transform:scale(.25);transform-origin:top left}.fa-lg{font-size:1.33333em;line-height:.75em;vertical-align:-.0667em}.fa-xs{font-size:.75em}.fa-sm{font-size:.875em}.fa-1x{font-size:1em}.fa-2x{font-size:2em}.fa-3x{font-size:3em}.fa-4x{font-size:4em}.fa-5x{font-size:5em}.fa-6x{font-size:6em}.fa-7x{font-size:7em}.fa-8x{font-size:8em}.fa-9x{font-size:9em}.fa-10x{font-size:10em}.fa-fw{text-align:center;width:1.25em}.fa-ul{list-style-type:none;margin-left:2.5em;padding-left:0}.fa-ul>li{position:relative}.fa-li{left:-2em;position:absolute;text-align:center;width:2em;line-height:inherit}.fa-border{border:.08em solid #eee;border-radius:.1em;padding:.2em .25em .15em}.fa-pull-left{float:left}.fa-pull-right{float:right}.fa.fa-pull-left,.fab.fa-pull-left,.fal.fa-pull-left,.far.fa-pull-left,.fas.fa-pull-left{margin-right:.3em}.fa.fa-pull-right,.fab.fa-pull-right,.fal.fa-pull-right,.far.fa-pull-right,.fas.fa-pull-right{margin-left:.3em}.fa-spin{animation:fa-spin 2s infinite linear}.fa-pulse{animation:fa-spin 1s infinite steps(8)}@keyframes fa-spin{0%{transform:rotate(0deg)}to{transform:rotate(1turn)}}.fa-rotate-90{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=1)";transform:rotate(90deg)}.fa-rotate-180{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=2)";transform:rotate(180deg)}.fa-rotate-270{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=3)";transform:rotate(270deg)}.fa-flip-horizontal{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=0, mirror=1)";transform:scaleX(-1)}.fa-flip-vertical{transform:scaleY(-1)}.fa-flip-horizontal.fa-flip-vertical,.fa-flip-vertical{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=2, mirror=1)"}.fa-flip-horizontal.fa-flip-vertical{transform:scale(-1)}:root .fa-flip-horizontal,:root .fa-flip-vertical,:root .fa-rotate-90,:root .fa-rotate-180,:root .fa-rotate-270{filter:none}.fa-stack{display:inline-block;height:2em;position:relative;width:2.5em}.fa-stack-1x,.fa-stack-2x{bottom:0;left:0;margin:auto;position:absolute;right:0;top:0}.svg-inline--fa.fa-stack-1x{height:1em;width:1.25em}.svg-inline--fa.fa-stack-2x{height:2em;width:2.5em}.fa-inverse{color:#fff}.sr-only{border:0;clip:rect(0,0,0,0);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px}.sr-only-focusable:active,.sr-only-focusable:focus{clip:auto;height:auto;margin:0;overflow:visible;position:static;width:auto} \ No newline at end of file diff --git a/static/js/fontawesome-all.min.js b/static/js/fontawesome-all.min.js index b08e9a6..498e4a0 100644 --- a/static/js/fontawesome-all.min.js +++ b/static/js/fontawesome-all.min.js @@ -1,5 +1,5 @@ /*! - * Font Awesome Free 5.3.1 by @fontawesome - https://fontawesome.com + * Font Awesome Free 5.6.0 by @fontawesome - https://fontawesome.com * License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) */ -!function(){"use strict";var c={};try{"undefined"!=typeof window&&(c=window)}catch(c){}var l=(c.navigator||{}).userAgent,h=void 0===l?"":l,z=c,v=(~h.indexOf("MSIE")||h.indexOf("Trident/"),"___FONT_AWESOME___"),m=function(){try{return!0}catch(c){return!1}}(),s=[1,2,3,4,5,6,7,8,9,10],e=s.concat([11,12,13,14,15,16,17,18,19,20]);["xs","sm","lg","fw","ul","li","border","pull-left","pull-right","spin","pulse","rotate-90","rotate-180","rotate-270","flip-horizontal","flip-vertical","stack","stack-1x","stack-2x","inverse","layers","layers-text","layers-counter"].concat(s.map(function(c){return c+"x"})).concat(e.map(function(c){return"w-"+c}));var a=z||{};a[v]||(a[v]={}),a[v].styles||(a[v].styles={}),a[v].hooks||(a[v].hooks={}),a[v].shims||(a[v].shims=[]);var t=a[v],M=Object.assign||function(c){for(var l=1;l>>0;h--;)l[h]=c[h];return l}function U(c){return c.classList?X(c.classList):(c.getAttribute("class")||"").split(" ").filter(function(c){return c})}function K(c,l){var h,z=l.split("-"),v=z[0],m=z.slice(1).join("-");return v!==c||""===m||(h=m,~w.indexOf(h))?null:m}function G(c){return(""+c).replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(//g,">")}function J(h){return Object.keys(h||{}).reduce(function(c,l){return c+(l+": ")+h[l]+";"},"")}function Q(c){return c.size!==W.size||c.x!==W.x||c.y!==W.y||c.rotate!==W.rotate||c.flipX||c.flipY}function Z(c){var l=c.transform,h=c.containerWidth,z=c.iconWidth;return{outer:{transform:"translate("+h/2+" 256)"},inner:{transform:"translate("+32*l.x+", "+32*l.y+") "+" "+("scale("+l.size/16*(l.flipX?-1:1)+", "+l.size/16*(l.flipY?-1:1)+") ")+" "+("rotate("+l.rotate+" 0 0)")},path:{transform:"translate("+z/2*-1+" -256)"}}}var $={x:0,y:0,width:"100%",height:"100%"},cc=function(c){var l=c.children,h=c.attributes,z=c.main,v=c.mask,m=c.transform,s=z.width,e=z.icon,a=v.width,t=v.icon,M=Z({transform:m,containerWidth:a,iconWidth:s}),f={tag:"rect",attributes:A({},$,{fill:"white"})},r={tag:"g",attributes:A({},M.inner),children:[{tag:"path",attributes:A({},e.attributes,M.path,{fill:"black"})}]},H={tag:"g",attributes:A({},M.outer),children:[r]},i="mask-"+D(),n="clip-"+D(),V={tag:"defs",children:[{tag:"clipPath",attributes:{id:n},children:[t]},{tag:"mask",attributes:A({},$,{id:i,maskUnits:"userSpaceOnUse",maskContentUnits:"userSpaceOnUse"}),children:[f,H]}]};return l.push(V,{tag:"rect",attributes:A({fill:"currentColor","clip-path":"url(#"+n+")",mask:"url(#"+i+")"},$)}),{children:l,attributes:h}},lc=function(c){var l=c.children,h=c.attributes,z=c.main,v=c.transform,m=J(c.styles);if(0"+s.map(bc).join("")+""}var gc=function(){};function Sc(c){return"string"==typeof(c.getAttribute?c.getAttribute(g):null)}var yc={replace:function(c){var l=c[0],h=c[1].map(function(c){return bc(c)}).join("\n");if(l.parentNode&&l.outerHTML)l.outerHTML=h+(E.keepOriginalSource&&"svg"!==l.tagName.toLowerCase()?"\x3c!-- "+l.outerHTML+" --\x3e":"");else if(l.parentNode){var z=document.createElement("span");l.parentNode.replaceChild(z,l),z.outerHTML=h}},nest:function(c){var l=c[0],h=c[1];if(~U(l).indexOf(E.replacementClass))return yc.replace(c);var z=new RegExp(E.familyPrefix+"-.*");delete h[0].attributes.style;var v=h[0].attributes.class.split(" ").reduce(function(c,l){return l===E.replacementClass||l.match(z)?c.toSvg.push(l):c.toNode.push(l),c},{toNode:[],toSvg:[]});h[0].attributes.class=v.toSvg.join(" ");var m=h.map(function(c){return bc(c)}).join("\n");l.setAttribute("class",v.toNode.join(" ")),l.setAttribute(g,""),l.innerHTML=m}};function wc(h,c){var z="function"==typeof c?c:gc;0===h.length?z():(r.requestAnimationFrame||function(c){return c()})(function(){var c=!0===E.autoReplaceSvg?yc.replace:yc[E.autoReplaceSvg]||yc.replace,l=Mc.begin("mutate");h.map(c),l(),z()})}var kc=!1;var xc=null;function Ac(c){if(e&&E.observeMutations){var v=c.treeCallback,m=c.nodeCallback,s=c.pseudoElementsCallback,l=c.observeMutationsRoot,h=void 0===l?H.body:l;xc=new e(function(c){kc||X(c).forEach(function(c){if("childList"===c.type&&0li{position:relative}.fa-li{left:-2em;position:absolute;text-align:center;width:2em;line-height:inherit}.fa-border{border:solid .08em #eee;border-radius:.1em;padding:.2em .25em .15em}.fa-pull-left{float:left}.fa-pull-right{float:right}.fa.fa-pull-left,.fab.fa-pull-left,.fal.fa-pull-left,.far.fa-pull-left,.fas.fa-pull-left{margin-right:.3em}.fa.fa-pull-right,.fab.fa-pull-right,.fal.fa-pull-right,.far.fa-pull-right,.fas.fa-pull-right{margin-left:.3em}.fa-spin{-webkit-animation:fa-spin 2s infinite linear;animation:fa-spin 2s infinite linear}.fa-pulse{-webkit-animation:fa-spin 1s infinite steps(8);animation:fa-spin 1s infinite steps(8)}@-webkit-keyframes fa-spin{0%{-webkit-transform:rotate(0);transform:rotate(0)}100%{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}@keyframes fa-spin{0%{-webkit-transform:rotate(0);transform:rotate(0)}100%{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}.fa-rotate-90{-webkit-transform:rotate(90deg);transform:rotate(90deg)}.fa-rotate-180{-webkit-transform:rotate(180deg);transform:rotate(180deg)}.fa-rotate-270{-webkit-transform:rotate(270deg);transform:rotate(270deg)}.fa-flip-horizontal{-webkit-transform:scale(-1,1);transform:scale(-1,1)}.fa-flip-vertical{-webkit-transform:scale(1,-1);transform:scale(1,-1)}.fa-flip-horizontal.fa-flip-vertical{-webkit-transform:scale(-1,-1);transform:scale(-1,-1)}:root .fa-flip-horizontal,:root .fa-flip-vertical,:root .fa-rotate-180,:root .fa-rotate-270,:root .fa-rotate-90{-webkit-filter:none;filter:none}.fa-stack{display:inline-block;height:2em;position:relative;width:2em}.fa-stack-1x,.fa-stack-2x{bottom:0;left:0;margin:auto;position:absolute;right:0;top:0}.svg-inline--fa.fa-stack-1x{height:1em;width:1em}.svg-inline--fa.fa-stack-2x{height:2em;width:2em}.fa-inverse{color:#fff}.sr-only{border:0;clip:rect(0,0,0,0);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px}.sr-only-focusable:active,.sr-only-focusable:focus{clip:auto;height:auto;margin:0;overflow:visible;position:static;width:auto}";if("fa"!==l||h!==c){var v=new RegExp("\\.fa\\-","g"),m=new RegExp("\\."+c,"g");z=z.replace(v,"."+l+"-").replace(m,"."+h)}return z};function zl(c){return{found:!0,width:c[0],height:c[1],icon:{tag:"path",attributes:{fill:"currentColor",d:c.slice(4)[0]}}}}function vl(){E.autoAddCss&&!tl&&(Y(hl()),tl=!0)}function ml(l,c){return Object.defineProperty(l,"abstract",{get:c}),Object.defineProperty(l,"html",{get:function(){return l.abstract.map(function(c){return bc(c)})}}),Object.defineProperty(l,"node",{get:function(){if(M){var c=H.createElement("div");return c.innerHTML=l.html,c.children}}}),l}function sl(c){var l=c.prefix,h=void 0===l?"fa":l,z=c.iconName;if(z)return pc(al.definitions,h,z)||pc(T.styles,h,z)}var el,al=new(function(){function c(){k(this,c),this.definitions={}}return x(c,[{key:"add",value:function(){for(var l=this,c=arguments.length,h=Array(c),z=0;z>>0;h--;)l[h]=c[h];return l}function W(c){return c.classList?D(c.classList):(c.getAttribute("class")||"").split(" ").filter(function(c){return c})}function Y(c,l){var h,z=l.split("-"),v=z[0],m=z.slice(1).join("-");return v!==c||""===m||(h=m,~x.indexOf(h))?null:m}function G(c){return"".concat(c).replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(//g,">")}function J(h){return Object.keys(h||{}).reduce(function(c,l){return c+"".concat(l,": ").concat(h[l],";")},"")}function Q(c){return c.size!==R.size||c.x!==R.x||c.y!==R.y||c.rotate!==R.rotate||c.flipX||c.flipY}function Z(c){var l=c.transform,h=c.containerWidth,z=c.iconWidth,v={transform:"translate(".concat(h/2," 256)")},m="translate(".concat(32*l.x,", ").concat(32*l.y,") "),s="scale(".concat(l.size/16*(l.flipX?-1:1),", ").concat(l.size/16*(l.flipY?-1:1),") "),e="rotate(".concat(l.rotate," 0 0)");return{outer:v,inner:{transform:"".concat(m," ").concat(s," ").concat(e)},path:{transform:"translate(".concat(z/2*-1," -256)")}}}var $={x:0,y:0,width:"100%",height:"100%"};function cc(c){var l=c.icons,h=l.main,z=l.mask,v=c.prefix,m=c.iconName,s=c.transform,e=c.symbol,a=c.title,M=c.extra,t=c.watchable,f=void 0!==t&&t,r=z.found?z:h,H=r.width,n=r.height,V="fa-w-".concat(Math.ceil(H/n*16)),i=[U.replacementClass,m?"".concat(U.familyPrefix,"-").concat(m):"",V].filter(function(c){return-1===M.classes.indexOf(c)}).concat(M.classes).join(" "),o={children:[],attributes:B({},M.attributes,{"data-prefix":v,"data-icon":m,class:i,role:"img",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 ".concat(H," ").concat(n)})};f&&(o.attributes[X]=""),a&&o.children.push({tag:"title",attributes:{id:o.attributes["aria-labelledby"]||"title-".concat(K())},children:[a]});var C,L,d,u,p,b,g,S,y,w,k,A,x,q,O,j,E,N,P,T,_,R,F,I=B({},o,{prefix:v,iconName:m,main:h,mask:z,transform:s,symbol:e,styles:M.styles}),D=z.found&&h.found?(L=(C=I).children,d=C.attributes,u=C.main,p=C.mask,b=C.transform,g=u.width,S=u.icon,y=p.width,w=p.icon,k=Z({transform:b,containerWidth:y,iconWidth:g}),A={tag:"rect",attributes:B({},$,{fill:"white"})},x={tag:"g",attributes:B({},k.inner),children:[{tag:"path",attributes:B({},S.attributes,k.path,{fill:"black"})}]},q={tag:"g",attributes:B({},k.outer),children:[x]},O="mask-".concat(K()),j="clip-".concat(K()),E={tag:"defs",children:[{tag:"clipPath",attributes:{id:j},children:[w]},{tag:"mask",attributes:B({},$,{id:O,maskUnits:"userSpaceOnUse",maskContentUnits:"userSpaceOnUse"}),children:[A,q]}]},L.push(E,{tag:"rect",attributes:B({fill:"currentColor","clip-path":"url(#".concat(j,")"),mask:"url(#".concat(O,")")},$)}),{children:L,attributes:d}):function(c){var l=c.children,h=c.attributes,z=c.main,v=c.transform,m=J(c.styles);if(0").concat(s.map(Lc).join(""),"")}var dc=function(){};function uc(c){return"string"==typeof(c.getAttribute?c.getAttribute(X):null)}var pc={replace:function(c){var l=c[0],h=c[1].map(function(c){return Lc(c)}).join("\n");if(l.parentNode&&l.outerHTML)l.outerHTML=h+(U.keepOriginalSource&&"svg"!==l.tagName.toLowerCase()?"\x3c!-- ".concat(l.outerHTML," --\x3e"):"");else if(l.parentNode){var z=document.createElement("span");l.parentNode.replaceChild(z,l),z.outerHTML=h}},nest:function(c){var l=c[0],h=c[1];if(~W(l).indexOf(U.replacementClass))return pc.replace(c);var z=new RegExp("".concat(U.familyPrefix,"-.*"));delete h[0].attributes.style;var v=h[0].attributes.class.split(" ").reduce(function(c,l){return l===U.replacementClass||l.match(z)?c.toSvg.push(l):c.toNode.push(l),c},{toNode:[],toSvg:[]});h[0].attributes.class=v.toSvg.join(" ");var m=h.map(function(c){return Lc(c)}).join("\n");l.setAttribute("class",v.toNode.join(" ")),l.setAttribute(X,""),l.innerHTML=m}};function bc(h,c){var z="function"==typeof c?c:dc;0===h.length?z():(H.requestAnimationFrame||function(c){return c()})(function(){var c=!0===U.autoReplaceSvg?pc.replace:pc[U.autoReplaceSvg]||pc.replace,l=sc.begin("mutate");h.map(c),l(),z()})}var gc=!1;var Sc=null;function yc(c){if(M&&U.observeMutations){var v=c.treeCallback,m=c.nodeCallback,s=c.pseudoElementsCallback,l=c.observeMutationsRoot,h=void 0===l?n.body:l;Sc=new M(function(c){gc||D(c).forEach(function(c){if("childList"===c.type&&0 Date: Fri, 14 Dec 2018 19:14:22 -0700 Subject: [PATCH 4/9] Remove is_empty() --- required.php | 42 ------------------------------------------ 1 file changed, 42 deletions(-) diff --git a/required.php b/required.php index c67229f..6753401 100644 --- a/required.php +++ b/required.php @@ -132,16 +132,6 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') { define("GET", true); } -/** - * @deprecated - * Checks if a string or whatever is empty. - * @param $str The thingy to check - * @return boolean True if it's empty or whatever. - */ -function is_empty($str) { - return (is_null($str) || !isset($str) || $str == ''); -} - function dieifnotloggedin() { if ($_SESSION['loggedin'] != true) { @@ -166,38 +156,6 @@ function checkDBError($specials = []) { } } -/* - * http://stackoverflow.com/a/20075147 - */ -if (!function_exists('base_url')) { - - function base_url($atRoot = FALSE, $atCore = FALSE, $parse = FALSE) { - if (isset($_SERVER['HTTP_HOST'])) { - $http = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off' ? 'https' : 'http'; - $hostname = $_SERVER['HTTP_HOST']; - $dir = str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']); - - $core = preg_split('@/@', str_replace($_SERVER['DOCUMENT_ROOT'], '', realpath(dirname(__FILE__))), NULL, PREG_SPLIT_NO_EMPTY); - $core = $core[0]; - - $tmplt = $atRoot ? ($atCore ? "%s://%s/%s/" : "%s://%s/") : ($atCore ? "%s://%s/%s/" : "%s://%s%s"); - $end = $atRoot ? ($atCore ? $core : $hostname) : ($atCore ? $core : $dir); - $base_url = sprintf($tmplt, $http, $hostname, $end); - } else - $base_url = 'http://localhost/'; - - if ($parse) { - $base_url = parse_url($base_url); - if (isset($base_url['path'])) - if ($base_url['path'] == '/') - $base_url['path'] = ''; - } - - return $base_url; - } - -} - function redirectIfNotLoggedIn() { if ($_SESSION['loggedin'] !== TRUE) { header('Location: ' . URL . '/index.php'); From 5b7ab6594636d1be9e5e0aec9f7d59a141eacdda Mon Sep 17 00:00:00 2001 From: Skylar Ittner Date: Fri, 14 Dec 2018 21:16:31 -0700 Subject: [PATCH 5/9] Make better API system, use new AccountHub API --- api.php | 33 +------- api/.htaccess | 5 ++ api/actions/ping.php | 9 +++ api/apisettings.php | 15 ++++ api/functions.php | 123 ++++++++++++++++++++++++++++++ api/index.php | 77 +++++++++++++++++++ lib/AccountHubApi.lib.php | 54 +++++++++++++ lib/Login.lib.php | 30 +------- lib/Notifications.lib.php | 30 +++----- lib/User.lib.php | 155 +++----------------------------------- mobile/index.php | 43 +++-------- settings.template.php | 2 +- 12 files changed, 314 insertions(+), 262 deletions(-) create mode 100644 api/.htaccess create mode 100644 api/actions/ping.php create mode 100644 api/apisettings.php create mode 100644 api/functions.php create mode 100644 api/index.php create mode 100644 lib/AccountHubApi.lib.php diff --git a/api.php b/api.php index 03178ea..b45877d 100644 --- a/api.php +++ b/api.php @@ -4,35 +4,4 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -/** - * Simple JSON API to allow other apps to access data from this app. - * - * Requests can be sent via either GET or POST requests. POST is recommended - * as it has a lower chance of being logged on the server, exposing unencrypted - * user passwords. - */ -require __DIR__ . '/required.php'; -header("Content-Type: application/json"); - -$username = $VARS['username']; -$password = $VARS['password']; -$user = User::byUsername($username); -if ($user->exists() !== true || Login::auth($username, $password) !== Login::LOGIN_OK) { - header("HTTP/1.1 403 Unauthorized"); - die("\"403 Unauthorized\""); -} - -// query max results -$max = 20; -if (preg_match("/^[0-9]+$/", $VARS['max']) === 1 && $VARS['max'] <= 1000) { - $max = (int) $VARS['max']; -} - -switch ($VARS['action']) { - case "ping": - $out = ["status" => "OK", "maxresults" => $max, "pong" => true]; - exit(json_encode($out)); - default: - header("HTTP/1.1 400 Bad Request"); - die("\"400 Bad Request\""); -} \ No newline at end of file +require __DIR__ . "/api/index.php"; \ No newline at end of file diff --git a/api/.htaccess b/api/.htaccess new file mode 100644 index 0000000..9a4efe4 --- /dev/null +++ b/api/.htaccess @@ -0,0 +1,5 @@ +# Rewrite for Nextcloud Notes API + + RewriteEngine on + RewriteRule ([a-zA-Z0-9]+) index.php?action=$1 [PT] + \ No newline at end of file diff --git a/api/actions/ping.php b/api/actions/ping.php new file mode 100644 index 0000000..c764967 --- /dev/null +++ b/api/actions/ping.php @@ -0,0 +1,9 @@ + [ + "load" => "ping.php", + "vars" => [ + ] + ] +]; diff --git a/api/functions.php b/api/functions.php new file mode 100644 index 0000000..78e84c1 --- /dev/null +++ b/api/functions.php @@ -0,0 +1,123 @@ + 5) { + for ($i = 2; $i < strlen($key) - 2; $i++) { + $resp[$i] = "*"; + } + } + return $resp; +} + +/** + * Check if the request is allowed + * @global type $VARS + * @global type $database + * @return bool true if the request should continue, false if the request is bad + */ +function authenticate(): bool { + global $VARS, $database; + if (empty($VARS['key'])) { + return false; + } else { + $key = $VARS['key']; + if ($database->has('apikeys', ['key' => $key]) !== TRUE) { + engageRateLimit(); + http_response_code(403); + Log::insert(LogType::API_BAD_KEY, null, "Key: " . $key); + return false; + } + } + return true; +} + +function checkVars($vars, $or = false) { + global $VARS; + $ok = []; + foreach ($vars as $key => $val) { + if (strpos($key, "OR") === 0) { + checkVars($vars[$key], true); + continue; + } + + // Only check type of optional variables if they're set, and don't + // mark them as bad if they're not set + if (strpos($key, " (optional)") !== false) { + $key = str_replace(" (optional)", "", $key); + if (empty($VARS[$key])) { + continue; + } + } else { + if (empty($VARS[$key])) { + $ok[$key] = false; + continue; + } + } + $checkmethod = "is_$val"; + if ($checkmethod($VARS[$key]) !== true) { + $ok[$key] = false; + } else { + $ok[$key] = true; + } + } + if ($or) { + $success = false; + $bad = ""; + foreach ($ok as $k => $v) { + if ($v) { + $success = true; + break; + } else { + $bad = $k; + } + } + if (!$success) { + http_response_code(400); + die("400 Bad request: variable $bad is missing or invalid"); + } + } else { + foreach ($ok as $key => $bool) { + if (!$bool) { + http_response_code(400); + die("400 Bad request: variable $key is missing or invalid"); + } + } + } +} diff --git a/api/index.php b/api/index.php new file mode 100644 index 0000000..a930798 --- /dev/null +++ b/api/index.php @@ -0,0 +1,77 @@ + 1) { + $VARS["action"] = $route[0]; + } + if (count($route) >= 2 && strpos($route[1], "?") !== 0) { + $VARS["key"] = $route[1]; + + for ($i = 2; $i < count($route); $i++) { + $key = explode("=", $route[$i], 2)[0]; + $val = explode("=", $route[$i], 2)[1]; + $VARS[$key] = $val; + } + } + + if (strpos($route[count($route) - 1], "?") === 0) { + $morevars = explode("&", substr($route[count($route) - 1], 1)); + foreach ($morevars as $var) { + $key = explode("=", $var, 2)[0]; + $val = explode("=", $var, 2)[1]; + $VARS[$key] = $val; + } + } +} + +if (!authenticate()) { + http_response_code(403); + die("403 Unauthorized"); +} + +if (empty($VARS['action'])) { + http_response_code(404); + die("404 No action specified"); +} + +if (!isset($APIS[$VARS['action']])) { + http_response_code(404); + die("404 Action not defined"); +} + +$APIACTION = $APIS[$VARS["action"]]; + +if (!file_exists(__DIR__ . "/actions/" . $APIACTION["load"])) { + http_response_code(404); + die("404 Action not found"); +} + +if (!empty($APIACTION["vars"])) { + checkVars($APIACTION["vars"]); +} + +require_once __DIR__ . "/actions/" . $APIACTION["load"]; diff --git a/lib/AccountHubApi.lib.php b/lib/AccountHubApi.lib.php new file mode 100644 index 0000000..06fae3b --- /dev/null +++ b/lib/AccountHubApi.lib.php @@ -0,0 +1,54 @@ + $action, + "key" => PORTAL_KEY + ]; + if (!is_null($data)) { + $content = array_merge($content, $data); + } + $options = [ + 'http' => [ + 'method' => 'POST', + 'content' => json_encode($content), + 'header' => "Content-Type: application/json\r\n" . + "Accept: application/json\r\n", + "ignore_errors" => true + ] + ]; + + $context = stream_context_create($options); + $result = file_get_contents(PORTAL_API, false, $context); + $response = json_decode($result, true); + if ($result === false || !AccountHubApi::checkHttpRespCode($http_response_header) || json_last_error() != JSON_ERROR_NONE) { + if ($throwex) { + throw new Exception($result); + } else { + sendError($result); + } + } + return $response; + } + + private static function checkHttpRespCode(array $headers): bool { + foreach ($headers as $header) { + if (preg_match("/HTTP\/[0-9]\.[0-9] [0-9]{3}.*/", $header)) { + $respcode = explode(" ", $header)[1] * 1; + if ($respcode >= 200 && $respcode < 300) { + return true; + } + } + } + return false; + } + +} diff --git a/lib/Login.lib.php b/lib/Login.lib.php index fe22a38..b136c6c 100644 --- a/lib/Login.lib.php +++ b/lib/Login.lib.php @@ -74,21 +74,7 @@ class Login { */ public static function checkLoginServer() { try { - $client = new GuzzleHttp\Client(); - - $response = $client - ->request('POST', PORTAL_API, [ - 'form_params' => [ - 'key' => PORTAL_KEY, - 'action' => "ping" - ] - ]); - - if ($response->getStatusCode() != 200) { - return false; - } - - $resp = json_decode($response->getBody(), TRUE); + $resp = AccountHubApi::get("ping"); if ($resp['status'] == "OK") { return true; } else { @@ -107,19 +93,7 @@ class Login { */ function checkAPIKey($key) { try { - $client = new GuzzleHttp\Client(); - - $response = $client - ->request('POST', PORTAL_API, [ - 'form_params' => [ - 'key' => $key, - 'action' => "ping" - ] - ]); - - if ($response->getStatusCode() === 200) { - return true; - } + $resp = AccountHubApi::get("ping", null, true); return false; } catch (Exception $e) { return false; diff --git a/lib/Notifications.lib.php b/lib/Notifications.lib.php index c1d93a9..812af26 100644 --- a/lib/Notifications.lib.php +++ b/lib/Notifications.lib.php @@ -32,27 +32,15 @@ class Notifications { $timestamp = date("Y-m-d H:i:s", strtotime($timestamp)); } - $client = new GuzzleHttp\Client(); - - $response = $client - ->request('POST', PORTAL_API, [ - 'form_params' => [ - 'key' => PORTAL_KEY, - 'action' => "addnotification", - 'uid' => $user->getUID(), - 'title' => $title, - 'content' => $content, - 'timestamp' => $timestamp, - 'url' => $url, - 'sensitive' => $sensitive - ] - ]); - - if ($response->getStatusCode() > 299) { - sendError("Login server error: " . $response->getBody()); - } - - $resp = json_decode($response->getBody(), TRUE); + $resp = AccountHubApi::get("addnotification", [ + 'uid' => $user->getUID(), + 'title' => $title, + 'content' => $content, + 'timestamp' => $timestamp, + 'url' => $url, + 'sensitive' => $sensitive + ] + ); if ($resp['status'] == "OK") { return $resp['id'] * 1; } else { diff --git a/lib/User.lib.php b/lib/User.lib.php index 7852e31..752cc88 100644 --- a/lib/User.lib.php +++ b/lib/User.lib.php @@ -17,22 +17,7 @@ class User { public function __construct(int $uid, string $username = "") { // Check if user exists - $client = new GuzzleHttp\Client(); - - $response = $client - ->request('POST', PORTAL_API, [ - 'form_params' => [ - 'key' => PORTAL_KEY, - 'action' => "userexists", - 'uid' => $uid - ] - ]); - - if ($response->getStatusCode() > 299) { - sendError("Login server error: " . $response->getBody()); - } - - $resp = json_decode($response->getBody(), TRUE); + $resp = AccountHubApi::get("userexists", ["uid" => $uid]); if ($resp['status'] == "OK" && $resp['exists'] === true) { $this->exists = true; } else { @@ -43,22 +28,7 @@ class User { if ($this->exists) { // Get user info - $client = new GuzzleHttp\Client(); - - $response = $client - ->request('POST', PORTAL_API, [ - 'form_params' => [ - 'key' => PORTAL_KEY, - 'action' => "userinfo", - 'uid' => $uid - ] - ]); - - if ($response->getStatusCode() > 299) { - sendError("Login server error: " . $response->getBody()); - } - - $resp = json_decode($response->getBody(), TRUE); + $resp = AccountHubApi::get("userinfo", ["uid" => $uid]); if ($resp['status'] == "OK") { $this->uid = $resp['data']['uid'] * 1; $this->username = $resp['data']['username']; @@ -71,22 +41,7 @@ class User { } public static function byUsername(string $username): User { - $client = new GuzzleHttp\Client(); - - $response = $client - ->request('POST', PORTAL_API, [ - 'form_params' => [ - 'key' => PORTAL_KEY, - 'username' => $username, - 'action' => "userinfo" - ] - ]); - - if ($response->getStatusCode() > 299) { - sendError("Login server error: " . $response->getBody()); - } - - $resp = json_decode($response->getBody(), TRUE); + $resp = AccountHubApi::get("userinfo", ["username" => $username]); if (!isset($resp['status'])) { sendError("Login server error: " . $resp); } @@ -105,22 +60,8 @@ class User { if (!$this->exists) { return false; } - $client = new GuzzleHttp\Client(); - - $response = $client - ->request('POST', PORTAL_API, [ - 'form_params' => [ - 'key' => PORTAL_KEY, - 'action' => "hastotp", - 'username' => $this->username - ] - ]); - - if ($response->getStatusCode() > 299) { - sendError("Login server error: " . $response->getBody()); - } - $resp = json_decode($response->getBody(), TRUE); + $resp = AccountHubApi::get("hastotp", ['username' => $this->username]); if ($resp['status'] == "OK") { return $resp['otp'] == true; } else { @@ -150,23 +91,7 @@ class User { * @return bool */ function checkPassword(string $password): bool { - $client = new GuzzleHttp\Client(); - - $response = $client - ->request('POST', PORTAL_API, [ - 'form_params' => [ - 'key' => PORTAL_KEY, - 'action' => "auth", - 'username' => $this->username, - 'password' => $password - ] - ]); - - if ($response->getStatusCode() > 299) { - sendError("Login server error: " . $response->getBody()); - } - - $resp = json_decode($response->getBody(), TRUE); + $resp = AccountHubApi::get("auth", ['username' => $this->username, 'password' => $password]); if ($resp['status'] == "OK") { return true; } else { @@ -178,23 +103,8 @@ class User { if (!$this->has2fa) { return true; } - $client = new GuzzleHttp\Client(); - - $response = $client - ->request('POST', PORTAL_API, [ - 'form_params' => [ - 'key' => PORTAL_KEY, - 'action' => "verifytotp", - 'username' => $this->username, - 'code' => $code - ] - ]); - - if ($response->getStatusCode() > 299) { - sendError("Login server error: " . $response->getBody()); - } - $resp = json_decode($response->getBody(), TRUE); + $resp = AccountHubApi::get("verifytotp", ['username' => $this->username, 'code' => $code]); if ($resp['status'] == "OK") { return $resp['valid']; } else { @@ -209,23 +119,7 @@ class User { * @return boolean TRUE if the user has the permission (or admin access), else FALSE */ function hasPermission(string $code): bool { - $client = new GuzzleHttp\Client(); - - $response = $client - ->request('POST', PORTAL_API, [ - 'form_params' => [ - 'key' => PORTAL_KEY, - 'action' => "permission", - 'username' => $this->username, - 'code' => $code - ] - ]); - - if ($response->getStatusCode() > 299) { - sendError("Login server error: " . $response->getBody()); - } - - $resp = json_decode($response->getBody(), TRUE); + $resp = AccountHubApi::get("permission", ['username' => $this->username, 'code' => $code]); if ($resp['status'] == "OK") { return $resp['has_permission']; } else { @@ -238,23 +132,7 @@ class User { * @return \AccountStatus */ function getStatus(): AccountStatus { - - $client = new GuzzleHttp\Client(); - - $response = $client - ->request('POST', PORTAL_API, [ - 'form_params' => [ - 'key' => PORTAL_KEY, - 'action' => "acctstatus", - 'username' => $this->username - ] - ]); - - if ($response->getStatusCode() > 299) { - sendError("Login server error: " . $response->getBody()); - } - - $resp = json_decode($response->getBody(), TRUE); + $resp = AccountHubApi::get("acctstatus", ['username' => $this->username]); if ($resp['status'] == "OK") { return AccountStatus::fromString($resp['account']); } else { @@ -263,23 +141,8 @@ class User { } function sendAlertEmail(string $appname = SITE_TITLE) { - $client = new GuzzleHttp\Client(); - - $response = $client - ->request('POST', PORTAL_API, [ - 'form_params' => [ - 'key' => PORTAL_KEY, - 'action' => "alertemail", - 'username' => $this->username, - 'appname' => SITE_TITLE - ] - ]); - - if ($response->getStatusCode() > 299) { - return "An unknown error occurred."; - } + $resp = AccountHubApi::get("alertemail", ['username' => $this->username, 'appname' => SITE_TITLE]); - $resp = json_decode($response->getBody(), TRUE); if ($resp['status'] == "OK") { return true; } else { diff --git a/mobile/index.php b/mobile/index.php index de36d52..dbb10f3 100644 --- a/mobile/index.php +++ b/mobile/index.php @@ -23,21 +23,7 @@ if ($VARS['action'] == "ping") { } function mobile_enabled() { - $client = new GuzzleHttp\Client(); - - $response = $client - ->request('POST', PORTAL_API, [ - 'form_params' => [ - 'key' => PORTAL_KEY, - 'action' => "mobileenabled" - ] - ]); - - if ($response->getStatusCode() > 299) { - return false; - } - - $resp = json_decode($response->getBody(), TRUE); + $resp = AccountHubApi::get("mobileenabled"); if ($resp['status'] == "OK" && $resp['mobile'] === TRUE) { return true; } else { @@ -46,26 +32,15 @@ function mobile_enabled() { } function mobile_valid($username, $code) { - $client = new GuzzleHttp\Client(); - - $response = $client - ->request('POST', PORTAL_API, [ - 'form_params' => [ - 'key' => PORTAL_KEY, - "code" => $code, - "username" => $username, - 'action' => "mobilevalid" - ] - ]); + try { + $resp = AccountHubApi::get("mobilevalid", ["code" => $code, "username" => $username], true); - if ($response->getStatusCode() > 299) { - return false; - } - - $resp = json_decode($response->getBody(), TRUE); - if ($resp['status'] == "OK" && $resp['valid'] === TRUE) { - return true; - } else { + if ($resp['status'] == "OK" && $resp['valid'] === TRUE) { + return true; + } else { + return false; + } + } catch (Exception $ex) { return false; } } diff --git a/settings.template.php b/settings.template.php index 2732b99..8711f01 100644 --- a/settings.template.php +++ b/settings.template.php @@ -22,7 +22,7 @@ define("SITE_TITLE", "Web App Template"); // URL of the AccountHub API endpoint -define("PORTAL_API", "http://localhost/accounthub/api.php"); +define("PORTAL_API", "http://localhost/accounthub/api/"); // URL of the AccountHub home page define("PORTAL_URL", "http://localhost/accounthub/home.php"); // AccountHub API Key From 61d660be69bda5a88f10b58e9d71fca532b442cb Mon Sep 17 00:00:00 2001 From: Skylar Ittner Date: Thu, 20 Dec 2018 23:24:47 -0700 Subject: [PATCH 6/9] Add FormBuilder --- langs/en/titles.json | 4 +- lib/FormBuilder.lib.php | 257 ++++++++++++++++++++++++++++++++++++++++ pages.php | 10 +- pages/form.php | 24 ++++ static/js/form.js | 16 +++ 5 files changed, 308 insertions(+), 3 deletions(-) create mode 100644 lib/FormBuilder.lib.php create mode 100644 pages/form.php create mode 100644 static/js/form.js diff --git a/langs/en/titles.json b/langs/en/titles.json index 6fbf103..4d745d0 100644 --- a/langs/en/titles.json +++ b/langs/en/titles.json @@ -1,4 +1,4 @@ { - "home": "Home", - "test": "Test" + "Home": "Home", + "Form": "Form" } diff --git a/lib/FormBuilder.lib.php b/lib/FormBuilder.lib.php new file mode 100644 index 0000000..fddbff2 --- /dev/null +++ b/lib/FormBuilder.lib.php @@ -0,0 +1,257 @@ +title = $title; + $this->icon = $icon; + $this->action = $action; + $this->method = $method; + } + + /** + * Set the title of the form. + * @param string $title + */ + public function setTitle(string $title) { + $this->title = $title; + } + + /** + * Set the icon for the form. + * @param string $icon FontAwesome icon (example: "fas fa-toilet-paper") + */ + public function setIcon(string $icon) { + $this->icon = $icon; + } + + /** + * Set the URL the form will submit to. + * @param string $action + */ + public function setAction(string $action) { + $this->action = $action; + } + + /** + * Set the form submission method (GET, POST, etc) + * @param string $method + */ + public function setMethod(string $method = "POST") { + $this->method = $method; + } + + /** + * Set the form ID. + * @param string $id + */ + public function setID(string $id = "editform") { + $this->id = $id; + } + + /** + * Add an input to the form. + * + * @param string $name Element name + * @param string $value Element value + * @param string $type Input type (text, number, date, select, tel...) + * @param bool $required If the element is required for form submission. + * @param string $id Element ID + * @param array $options Array of [value => text] pairs for a select element + * @param string $label Text label to display near the input + * @param string $icon FontAwesome icon (example: "fas fa-toilet-paper") + * @param int $width Bootstrap column width for the input, out of 12. + * @param int $minlength Minimum number of characters for the input. + * @param int $maxlength Maximum number of characters for the input. + * @param string $pattern Regex pattern for custom client-side validation. + * @param string $error Message to show if the input doesn't validate. + */ + public function addInput(string $name, string $value = "", string $type = "text", bool $required = true, string $id = null, array $options = null, string $label = "", string $icon = "", int $width = 4, int $minlength = 1, int $maxlength = 100, string $pattern = "", string $error = "") { + $item = [ + "name" => $name, + "value" => $value, + "type" => $type, + "required" => $required, + "label" => $label, + "icon" => $icon, + "width" => $width, + "minlength" => $minlength, + "maxlength" => $maxlength + ]; + if (!empty($id)) { + $item["id"] = $id; + } + if (!empty($options) && $type == "select") { + $item["options"] = $options; + } + if (!empty($pattern)) { + $item["pattern"] = $pattern; + } + if (!empty($error)) { + $item["error"] = $error; + } + $this->items[] = $item; + } + + /** + * Add a button to the form. + * + * @param string $text Text string to show on the button. + * @param string $icon FontAwesome icon to show next to the text. + * @param string $href If not null, the button will actually be a hyperlink. + * @param string $type Usually "button" or "submit". Ignored if $href is set. + * @param string $id The element ID. + * @param string $name The element name for the button. + * @param string $value The form value for the button. Ignored if $name is null. + * @param string $class The CSS classes for the button, if a standard success-colored one isn't right. + */ + public function addButton(string $text, string $icon = "", string $href = null, string $type = "button", string $id = null, string $name = null, string $value = "", string $class = "btn btn-success") { + $button = [ + "text" => $text, + "icon" => $icon, + "class" => $class, + "type" => $type, + "id" => $id, + "href" => $href, + "name" => $name, + "value" => $value + ]; + $this->buttons[] = $button; + } + + /** + * Add a hidden input. + * @param string $name + * @param string $value + */ + public function addHiddenInput(string $name, string $value) { + $this->hiddenitems[$name] = $value; + } + + /** + * Generate the form HTML. + * @param bool $echo If false, returns HTML string instead of outputting it. + */ + public function generate(bool $echo = true) { + $html = << +
+

+
+ $this->title +
+

+ +
+
+HTMLTOP; + + foreach ($this->items as $item) { + $required = $item["required"] ? "required" : ""; + $id = empty($item["id"]) ? "" : "id=\"$item[id]\""; + $pattern = empty($item["pattern"]) ? "" : "pattern=\"$item[pattern]\""; + + $itemhtml = ""; + $itemhtml .= << +
+ +
+
+ +
+ITEMTOP; + if (empty($item['type']) || $item['type'] != "select") { + $itemhtml .= << +INPUT; + } else { + $itemhtml .= <<"; + } + + if (!empty($item["error"])) { + $itemhtml .= << + $item[error] +
+ERROR; + } + $itemhtml .= << +
+
\n +ITEMBOTTOM; + $html .= $itemhtml; + } + + $html .= << +
+HTMLBOTTOM; + + if (!empty($this->buttons)) { + $html .= "\n
"; + foreach ($this->buttons as $btn) { + $btnhtml = ""; + $inner = " $btn[text]"; + $id = empty($btn['id']) ? "" : "id=\"$btn[id]\""; + if (!empty($btn['href'])) { + $btnhtml = "$inner"; + } else { + $name = empty($btn['name']) ? "" : "name=\"$btn[name]\""; + $value = (!empty($btn['name']) && !empty($btn['value'])) ? "value=\"$btn[value]\"" : ""; + $btnhtml = ""; + } + $html .= "\n $btnhtml"; + } + $html .= "\n
"; + } + + $html .= "\n
"; + foreach ($this->hiddenitems as $name => $value) { + $value = htmlentities($value); + $html .= "\n "; + } + $html .= "\n\n"; + + if ($echo) { + echo $html; + } + return $html; + } + +} diff --git a/pages.php b/pages.php index ad2a84f..fe7cc1c 100644 --- a/pages.php +++ b/pages.php @@ -7,11 +7,19 @@ // List of pages and metadata define("PAGES", [ "home" => [ - "title" => "home", + "title" => "Home", "navbar" => true, "icon" => "fas fa-home" ], "404" => [ "title" => "404 error" + ], + "form" => [ + "title" => "Form", + "navbar" => true, + "icon" => "fas fa-file-alt", + "scripts" => [ + "static/js/form.js" + ] ] ]); \ No newline at end of file diff --git a/pages/form.php b/pages/form.php new file mode 100644 index 0000000..7cd7fdd --- /dev/null +++ b/pages/form.php @@ -0,0 +1,24 @@ +setID("sampleform"); + +$form->addHiddenInput("page", "form"); + +$form->addInput("name", "John", "text", true, null, null, "Your name", "fas fa-user", 6, 5, 20, "John(ny)?|Steve", "Invalid name, please enter John, Johnny, or Steve."); +$form->addInput("location", "", "select", true, null, ["1" => "Here", "2" => "There"], "Location", "fas fa-map-marker"); + +$form->addButton("Submit", "fas fa-save", null, "submit", "savebtn"); + +$form->generate(); \ No newline at end of file diff --git a/static/js/form.js b/static/js/form.js new file mode 100644 index 0000000..21c9f53 --- /dev/null +++ b/static/js/form.js @@ -0,0 +1,16 @@ +/* + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + + +$("#savebtn").click(function (event) { + var form = $("#sampleform"); + + if (form[0].checkValidity() === false) { + event.preventDefault(); + event.stopPropagation(); + } + form.addClass('was-validated'); +}); \ No newline at end of file From f1a85f47fd6b7e8caef810d7f77db377ba50b29c Mon Sep 17 00:00:00 2001 From: Skylar Ittner Date: Thu, 20 Dec 2018 23:25:34 -0700 Subject: [PATCH 7/9] Add comment --- api.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/api.php b/api.php index b45877d..d68b923 100644 --- a/api.php +++ b/api.php @@ -4,4 +4,6 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +// Load in new API from legacy location (a.k.a. here) require __DIR__ . "/api/index.php"; \ No newline at end of file From c179ed7ebbbe04670c0146889ac1d026e8770976 Mon Sep 17 00:00:00 2001 From: Skylar Ittner Date: Thu, 20 Dec 2018 23:45:45 -0700 Subject: [PATCH 8/9] Make settings.php an array, not a bunch of defines --- app.php | 10 +++--- index.php | 16 ++++----- lib/AccountHubApi.lib.php | 6 ++-- lib/User.lib.php | 8 +++-- required.php | 22 ++++++------ settings.template.php | 75 ++++++++++++++++----------------------- 6 files changed, 65 insertions(+), 72 deletions(-) diff --git a/app.php b/app.php index b74d422..607437e 100644 --- a/app.php +++ b/app.php @@ -39,7 +39,7 @@ header("Link: ; rel=preload; as=script", fals - <?php echo SITE_TITLE; ?> + <?php echo $SETTINGS['site_title']; ?> @@ -127,7 +127,7 @@ END; - + diff --git a/index.php b/index.php index 1f8f76f..f3a816c 100644 --- a/index.php +++ b/index.php @@ -21,7 +21,7 @@ if (Login::checkLoginServer()) { if (empty($VARS['progress'])) { // Easy way to remove "undefined" warnings. } else if ($VARS['progress'] == "1") { - if (!CAPTCHA_ENABLED || (CAPTCHA_ENABLED && Login::verifyCaptcha($VARS['captcheck_session_code'], $VARS['captcheck_selected_answer'], CAPTCHA_SERVER . "/api.php"))) { + if (!$SETTINGS['captcha']['enabled'] || ($SETTINGS['captcha']['enabled'] && Login::verifyCaptcha($VARS['captcheck_session_code'], $VARS['captcheck_selected_answer'], $SETTINGS['captcha']['server'] . "/api.php"))) { $autherror = ""; $user = User::byUsername($VARS['username']); if ($user->exists()) { @@ -41,7 +41,7 @@ if (Login::checkLoginServer()) { break; case "ALERT_ON_ACCESS": $mail_resp = $user->sendAlertEmail(); - if (DEBUG) { + if ($SETTINGS['debug']) { var_dump($mail_resp); } $username_ok = true; @@ -105,15 +105,15 @@ header("Link: ; rel=preload; as=script", fals - <?php echo SITE_TITLE; ?> + <?php echo $SETTINGS['site_title']; ?> - - + + @@ -140,7 +140,7 @@ header("Link: ; rel=preload; as=script", fals ?> " required="required" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" autofocus />
" required="required" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" />
- +

@@ -165,8 +165,8 @@ header("Link: ; rel=preload; as=script", fals diff --git a/lib/AccountHubApi.lib.php b/lib/AccountHubApi.lib.php index 06fae3b..4d23f9e 100644 --- a/lib/AccountHubApi.lib.php +++ b/lib/AccountHubApi.lib.php @@ -9,9 +9,11 @@ class AccountHubApi { public static function get(string $action, array $data = null, bool $throwex = false) { + global $SETTINGS; + $content = [ "action" => $action, - "key" => PORTAL_KEY + "key" => $SETTINGS['accounthub']['key'] ]; if (!is_null($data)) { $content = array_merge($content, $data); @@ -27,7 +29,7 @@ class AccountHubApi { ]; $context = stream_context_create($options); - $result = file_get_contents(PORTAL_API, false, $context); + $result = file_get_contents($SETTINGS['accounthub']['api'], false, $context); $response = json_decode($result, true); if ($result === false || !AccountHubApi::checkHttpRespCode($http_response_header) || json_last_error() != JSON_ERROR_NONE) { if ($throwex) { diff --git a/lib/User.lib.php b/lib/User.lib.php index 752cc88..763acc5 100644 --- a/lib/User.lib.php +++ b/lib/User.lib.php @@ -140,8 +140,12 @@ class User { } } - function sendAlertEmail(string $appname = SITE_TITLE) { - $resp = AccountHubApi::get("alertemail", ['username' => $this->username, 'appname' => SITE_TITLE]); + function sendAlertEmail(string $appname = null) { + global $SETTINGS; + if (is_null($appname)) { + $appname = $SETTINGS['site_title']; + } + $resp = AccountHubApi::get("alertemail", ['username' => $this->username, 'appname' => $SETTINGS['site_title']]); if ($resp['status'] == "OK") { return true; diff --git a/required.php b/required.php index 6753401..3fe1060 100644 --- a/required.php +++ b/required.php @@ -32,7 +32,7 @@ session_start(); // stick some cookies in it // renew session cookie setcookie(session_name(), session_id(), time() + $session_length, "/", false, false); -$captcha_server = (CAPTCHA_ENABLED === true ? preg_replace("/http(s)?:\/\//", "", CAPTCHA_SERVER) : ""); +$captcha_server = ($SETTINGS['captcha']['enabled'] === true ? preg_replace("/http(s)?:\/\//", "", $SETTINGS['captcha']['server']) : ""); if ($_SESSION['mobile'] === TRUE) { header("Content-Security-Policy: " . "default-src 'self';" @@ -69,7 +69,7 @@ foreach ($libs as $lib) { require_once $lib; } -$Strings = new Strings(LANGUAGE); +$Strings = new Strings($SETTINGS['language']); /** * Kill off the running process and spit out an error message @@ -93,7 +93,7 @@ function sendError($error) { . "

" . htmlspecialchars($error) . "

"); } -date_default_timezone_set(TIMEZONE); +date_default_timezone_set($SETTINGS['timezone']); // Database settings // Also inits database and stuff @@ -102,12 +102,12 @@ use Medoo\Medoo; $database; try { $database = new Medoo([ - 'database_type' => DB_TYPE, - 'database_name' => DB_NAME, - 'server' => DB_SERVER, - 'username' => DB_USER, - 'password' => DB_PASS, - 'charset' => DB_CHARSET + 'database_type' => $SETTINGS['database']['type'], + 'database_name' => $SETTINGS['database']['name'], + 'server' => $SETTINGS['database']['server'], + 'username' => $SETTINGS['database']['user'], + 'password' => $SETTINGS['database']['password'], + 'charset' => $SETTINGS['database']['charset'] ]); } catch (Exception $ex) { //header('HTTP/1.1 500 Internal Server Error'); @@ -115,7 +115,7 @@ try { } -if (!DEBUG) { +if (!$SETTINGS['debug']) { error_reporting(0); } else { error_reporting(E_ALL); @@ -158,7 +158,7 @@ function checkDBError($specials = []) { function redirectIfNotLoggedIn() { if ($_SESSION['loggedin'] !== TRUE) { - header('Location: ' . URL . '/index.php'); + header('Location: ' . $SETTINGS['url'] . '/index.php'); die(); } } diff --git a/settings.template.php b/settings.template.php index 8711f01..2e346e3 100644 --- a/settings.template.php +++ b/settings.template.php @@ -1,47 +1,34 @@ false, + "database" => [ + "type" => "mysql", + "name" => "app", + "server" => "localhost", + "user" => "app", + "password" => "", + "charset" => "utf8" + ], + "site_title" => "Web App Template", + "accounthub" => [ + "api" => "http://localhost/accounthub/api/", + "home" => "http://localhost/accounthub/home.php", + "key" => "123" + ], + "timezone" => "America/Denver", + "captcha" => [ + "enabled" => false, + "server" => "https://captcheck.netsyms.com" + ], + "language" => "en", + "footer_text" => "", + "copyright" => "Netsyms Technologies", + "url" => "." +]; \ No newline at end of file From 129efd13c737ed714e1f5a83b4cb2e122a3569f3 Mon Sep 17 00:00:00 2001 From: Skylar Ittner Date: Thu, 20 Dec 2018 23:54:25 -0700 Subject: [PATCH 9/9] Add documentation comments to settings --- settings.template.php | 34 +++++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/settings.template.php b/settings.template.php index 2e346e3..75a1896 100644 --- a/settings.template.php +++ b/settings.template.php @@ -6,8 +6,18 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +// Settings for the app. +// Copy to settings.php and customize. + $SETTINGS = [ + // Whether to output debugging info like PHP notices, warnings, + // and stacktraces. + // Turning this on in production is a security risk and can sometimes break + // things, such as JSON output where extra content is not expected. "debug" => false, + + // Database connection settings + // See http://medoo.in/api/new for info "database" => [ "type" => "mysql", "name" => "app", @@ -16,19 +26,41 @@ $SETTINGS = [ "password" => "", "charset" => "utf8" ], + + // Name of the app. "site_title" => "Web App Template", + + // Settings for connecting to the AccountHub server. "accounthub" => [ + // URL for the API endpoint "api" => "http://localhost/accounthub/api/", + // URL of the home page "home" => "http://localhost/accounthub/home.php", + // API key "key" => "123" ], + + // For supported values, see http://php.net/manual/en/timezones.php "timezone" => "America/Denver", + + // Use Captcheck on login screen to slow down bots + // https://captcheck.netsyms.com "captcha" => [ "enabled" => false, "server" => "https://captcheck.netsyms.com" ], + + // Language to use for localization. See langs folder to add a language. "language" => "en", + + // Shown in the footer of all the pages. "footer_text" => "", + + // Also shown in the footer, but with "Copyright " in front. "copyright" => "Netsyms Technologies", + + // Base URL for building links relative to the location of the app. + // Only used when there's no good context for the path. + // The default is almost definitely fine. "url" => "." -]; \ No newline at end of file +];