Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Impotence
Nov 8, 2010
Lipstick Apathy
Yeah, but you may be violating local laws and other stuff, if, for example, you are sending addresses, phone numbers, and other PII across the internet without SSL

Adbot
ADBOT LOVES YOU

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.

Biowarfare posted:

Yeah, but you may be violating local laws and other stuff, if, for example, you are sending addresses, phone numbers, and other PII across the internet without SSL

Had not occurred to me in the slightest. Haha. Jesus nothing is ever simple.

Experto Crede
Aug 19, 2008

Keep on Truckin'

Newf posted:

That's all awful, yeah, but my scope here is small. I'm putting something together here for a family member who wants an online booking/contact system on the cheap for his personal business. He already has his godaddy hosting at an extremely low price.

Are these security concerns bad enough that I shouldn't proceed? Would it suffice to configure the remote connection as readonly? I don't expect that there's a great threat of cyber-espionage in the local roofing market.

Based on this, might it not be better to spin off a digitalocean VM to run a MySQL instance?

Bit more work in the setup, but a good learning exercise and you can have significantly more control.

Experto Crede fucked around with this message at 10:27 on Aug 18, 2015

Experto Crede
Aug 19, 2008

Keep on Truckin'
Is it possible to use sessions via CLI scripts? I have a script which needs to pull data from a exec call, but this command can sometimes be a bit slow, so I'd rather not run it every time if possible.

As a test I slapped this together:

code:
<?php
session_start();

if(!isset($_SESSION['commandOutput']))
{
        $_SESSION['commandOutput'] = exec('command');
}

echo $_SESSION['commandOutput'];
Which works and gives the output of the command, but the command is definitely being run each time, because if I check the state of $_SESSION before the if check by var dumping it, it shows up as empty. So it seems the session data isn't being saved across runs which is what I'm trying to have happen.

Is there something I can do here to make it work?

Impotence
Nov 8, 2010
Lipstick Apathy
if you don't want to use redis or some kind of job queue i'd just file_put_contents and file_get_contents it or something

Experto Crede
Aug 19, 2008

Keep on Truckin'

Biowarfare posted:

if you don't want to use redis or some kind of job queue i'd just file_put_contents and file_get_contents it or something

Yeah, that's actually a much easier way to do it in this case. Thanks!

Impotence
Nov 8, 2010
Lipstick Apathy
make sure you set filename ot something like __DIR__ . "/cache/exec.txt"; or something, bash scripts or php from cron or whatever tends to get a bit wonky current-working-directory wise

bigmandan
Sep 11, 2001

lol internet
College Slice
I've been working on a small problem and I have a solution that works for me, but I'm concerned about style and correctness. The problem appears to be similar to a 0-1 knapsack problem, only I have multiple knapsacks.

Is what I came up with decent, or am I a coding horror?


edit:

After giving it some thought, what I came up with was pretty terrible. I think I came up with a better solution. Maybe.

bigmandan fucked around with this message at 21:42 on Sep 3, 2015

kedo
Nov 27, 2007

Hi thread. I feel like this might be a dumb question but I'm going to ask anyways.

Is there a way to generate an XML file automagically with a big ol' chunk of data (eg. an array), based on an existing XML schema? I'm in the process of writing a WordPress plugin that exports posts in a specific XML format and I have an xsd sitting here collecting dust. Currently I'm using simplexml to create it from scratch as best I can to match the schema, but that seems stupid and time consuming.

Can anyone point me in a more intelligent direction?

putin is a cunt
Apr 5, 2007

BOY DO I SURE ENJOY TRASH. THERE'S NOTHING MORE I LOVE THAN TO SIT DOWN IN FRONT OF THE BIG SCREEN AND EAT A BIIIIG STEAMY BOWL OF SHIT. WARNER BROS CAN COME OVER TO MY HOUSE AND ASSFUCK MY MOM WHILE I WATCH AND I WOULD CERTIFY IT FRESH, NO QUESTION

Newf posted:

Had not occurred to me in the slightest. Haha. Jesus nothing is ever simple.

I'm sure there's a simple solution, it's just that usually the simple solution is not to write your own software. What is the actual problem you're trying to solve? There may be some existing solutions out there that you can use.

Experto Crede
Aug 19, 2008

Keep on Truckin'
I'm trying to parse a webpage. I've managed to extract the table I want, but now need to pull the data from it.

So far I have a variable containing the <table>...</table> as a string in it, but now want to loop through and create an array of each tr, with the td being items in the array.

So for example I'd want to take this:

code:
<tr>
    <td>foo</td>
    <td>bar</td>
</tr>
<tr>
    <td>foobar</td>
    <td>barfoo</td>
</tr>
And turn it to:

code:
Array
(
    [0] => Array
        (
            [0] => foo
            [1] => bar
        )
    [1] => Array
        (
            [0] => foobar
            [1] => barfoo
        )
)
What'd be the neatest way of doing this? I've tried using regex but it's a bit too messy and I'm sure there's better ways.

McGlockenshire
Dec 16, 2005

GOLLOCKS!
You're probably looking for simplehtmldom or phpquery, which will let you get to the DOM nodes in a happier way than the built in DOM methods.

Do not attempt to parse HTML with regexes for serious purposes.

Forgall
Oct 16, 2012

by Azathoth
When installing an extension with "pecl install" is there a way to pass parameters to its ./configure script?

revmoo
May 25, 2006

#basta
Anyone in here done anything with Oauth2? I'm struggling to implement this lib:

https://github.com/bshaffer/oauth2-server-php

The documentation is almost nonexistant so I'm having to practically reverse engineer it to get it to work. I've gotten pretty far along, but I'm having a hard time figuring out how to authenticate users. I've got an oauth_clients and oauth_users table, but there is nothing in the docs that explains how to store user credentials, what type of hashing to use, etc.

Basically, I'm trying to set up this flow:

User wants to login to our system. Their admin has configured their user/pass within their platform so that user only needs to click a link to login to our system. Once the link is clicked,

- Their system submits user/pass/client_id/client_secret
- Our system confirms these credentials, returns a token
- Their system redirects their user to the appropriate endpoint URL on our system with the given token
- Our system reads the token, verifies it, logs the user in

This all seems pretty straightforward, but I'm stuck with how to go about using the lib to auth my users. Again, it looks like the library expects me to save passwords and client secrets with some sort of hashing but none of this is documented at all. I really just want to handle user auth by myself and not involve Oauth2, but I at least need to figure out the hashing for client secrets.

According to the Oauth site there's a second PHP lib, but it's even less documented than this one. I'm about half a step away from implementing Oauth2 from scratch from the spec, but I'd prefer to just get this working if possible.

EDIT: Figured out a way to force Oauth2 to utilize my own auth by basically confirming credentials on my end and then populating the storage object with a memory array containing the submitted credentials, or nothing if the auth failed. Then Oauth will respond to the user properly. Seems backwards, but does in fact work. Then for client secrets, I just call setClientDetails() the same way once I've confirmed the creds are correct. It's really ugly, but it does in fact work.

revmoo fucked around with this message at 20:50 on Sep 15, 2015

stoops
Jun 11, 2001
I'm trying to read certain sections of a file.

The format for one file is something like:

----read file ---
<Box0>
<TimeIndex>0</TimeIndex>
<NumberSources>1</NumberSources>
<Source0>
<SourceType>CDF</SourceType>
<SourceCDF>
</Box0>

<Box1>
<TimeIndex>0</TimeIndex>
<NumberSources>1</NumberSources>
<Source0>
<SourceType>CDF</SourceType>
<SourceCDF>
</Box1>
----end read file ---


The box numbers could be upto 100 boxes per file.

Say I want the info for box1. How do I go about getting the full text, as in everything from "<Box0>" to "</Box0>" ?

Any help or point in the right direction is appreciated.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

stoops posted:

Say I want the info for box1. How do I go about getting the full text, as in everything from "<Box0>" to "</Box0>" ?

You don't actually want to do this. You have XML data - you want to use an XML parser, which will provide you with a more appropriate view on the data than trying to process it as raw text.

Experto Crede
Aug 19, 2008

Keep on Truckin'

stoops posted:

I'm trying to read certain sections of a file.

The format for one file is something like:

----read file ---
<Box0>
<TimeIndex>0</TimeIndex>
<NumberSources>1</NumberSources>
<Source0>
<SourceType>CDF</SourceType>
<SourceCDF>
</Box0>

<Box1>
<TimeIndex>0</TimeIndex>
<NumberSources>1</NumberSources>
<Source0>
<SourceType>CDF</SourceType>
<SourceCDF>
</Box1>
----end read file ---


The box numbers could be upto 100 boxes per file.

Say I want the info for box1. How do I go about getting the full text, as in everything from "<Box0>" to "</Box0>" ?

Any help or point in the right direction is appreciated.

$xml = simplexml_load_file('path/to/file');

If you must pull the string out for whatever reason, then use preg_match like this:

preg_match('#<Box0>(.*)</Box0>#s', $xmlstring, $output);

Where $output[0] will be the string.

stoops
Jun 11, 2001

Jabor posted:

You don't actually want to do this. You have XML data - you want to use an XML parser, which will provide you with a more appropriate view on the data than trying to process it as raw text.
Jabor, you are correct on the xml. I'm using cakephp so I ended up using their XML parser.

Experto Crede posted:

preg_match('#<Box0>(.*)</Box0>#s', $xmlstring, $output);
Experto Crede, the preg match was exactly what I needed.

Thanks, both

substitute
Aug 30, 2003

you for my mum

stoops posted:

Jabor, you are correct on the xml. I'm using cakephp so I ended up using their XML parser.

Experto Crede, the preg match was exactly what I needed.

Thanks, both

Which version of Cake are using by the way?

We're still using 2.6.7 at work, with no down time right now to try out version 3+, and compare any other modern frameworks.

stoops
Jun 11, 2001

substitute posted:

Which version of Cake are using by the way?

We're still using 2.6.7 at work, with no down time right now to try out version 3+, and compare any other modern frameworks.

All the websites I've worked on vary on the version. All are above 3.0.

I know i'm not taking full advantage of many of the features Cake offers, but the stuff I've done, I haven't had much of a problem. I'm not the best php developer, so mayb other frameworks are better, but I like using Cake.

revmoo
May 25, 2006

#basta
Anybody know how to define a column as timestamp in Laravel?

ie. I have updated_at, created_at, and a third column which I also want Laravel to know is a timestamp (so that when I call find() on the model I can specify timezone on the carbon object)

DarkLotus
Sep 30, 2001

Lithium Hosting
Personal, Reseller & VPS Hosting
30-day no risk Free Trial &
90-days Money Back Guarantee!

revmoo posted:

Anybody know how to define a column as timestamp in Laravel?

ie. I have updated_at, created_at, and a third column which I also want Laravel to know is a timestamp (so that when I call find() on the model I can specify timezone on the carbon object)

in your model define a $dates array.
php:
<?
class Account extends \Eloquent {

    use SoftDeletingTrait;
    protected $dates = ['deleted_at'];
}
?>
http://laravel.com/docs/5.0/eloquent#soft-deleting

revmoo
May 25, 2006

#basta
Of course it's under 'soft deleting'. haha thanks

DarkLotus
Sep 30, 2001

Lithium Hosting
Personal, Reseller & VPS Hosting
30-day no risk Free Trial &
90-days Money Back Guarantee!

revmoo posted:

Of course it's under 'soft deleting'. haha thanks

Out of curiousity, what does your query look like?

revmoo
May 25, 2006

#basta
Not using a query, just the plain ORM. I'm running a background poller task that stores a completed_time timestamp that I display in the UI. I needed that column to be a Carbon object so I could render the appropriate time from UTC using the Laravel built-in methods.

Could probably use updated_at, but I've got some additional logic that the third timestamp wraps around.

Splinter
Jul 4, 2003
Cowabunga!
I'm inexperienced with references in PHP and am looking at a lot of code structured like this:

code:
function foo(&$bar)
{
    // modify $bar    

    return $bar;
}
$bar = foo($bar);
I believe the point of passing $bar by reference in this case is to avoid copying a large array, but isn't it unnecessary to return $bar and reassign it to itself?

Is this equivalent to:
code:
function foo(&$bar)
{
    // modify $bar
}
foo($bar);
Or are there unintended consequences with the first example (e.g., does this actually result in $bar being copied at some point)?

What's the best practice for functions like this?

IT BEGINS
Jan 15, 2009

I don't know how to make analogies
Having that return on top of the pass by reference is redundant unless you for some reason want to both modify and copy the array, which is still mostly pointless.

Best practice is to work with arrays functionally whenever possible, and not worry too much about whether or not you are copying a large structure unless you're having memory issues or things are running much slower than expected. Also, I think it best to avoid passing things by reference whenever possible. It's usually more hassle than it's worth, especially because unlike C it's not clear when you call a function whether or not some of your parameters might end up modified.

Basically, prefer

php:
<?

function foo(array $bar)
{
    // modify $bar
    return $bar
}

$b = foo($b);

?>
over

php:
<?

function foo(array &$bar)
{
    // modify $bar
}

foo($b);

?>
pretty much all the time.

IT BEGINS fucked around with this message at 23:35 on Oct 14, 2015

v1nce
Sep 19, 2004

Plant your brassicas in may and cover them in mulch.
I've seen code like that before in instances where the function never used to be pass-by-reference, and was changed to be pass-by-reference to save memory.

Yes, the return/assign is redundant if you do this, however it is ever so slightly more readable for inexperienced developers who aren't expecting pass-by-reference modifications. That's not a great reason to do it, though. Also as far as I'm aware, there are no side effects.

The only guideline that's really appropriate is to say that your function name should be verbose about the action it's going to perform. Be it an object (which is always passed by reference), an array, or a scalar value; if it's going to modify the data you pass it then its name should probably reflect that. Also make sure you have sufficient comments to back up what the function name says, as to dispel any ambiguity. Comments are especially important for functions which both modify arguments and return data at the same time.

Here's a less than stellar example:
code:
/**
 * Modify the $data array, and reformat all the dates to ISO8601
 * Returns a flat list of entries with invalid dates
 * @param array $data
 * @return array
 */
public function modifyDateFormats(array &$data)
{
    // ...
}
I wouldn't say to avoid passing by reference, just do it sparingly. If you end up doing a deep sequence of pass-by-reference with an array then it can become difficult to both understand and debug that code.

Splinter
Jul 4, 2003
Cowabunga!
Thanks guys. This:

quote:

I've seen code like that before in instances where the function never used to be pass-by-reference, and was changed to be pass-by-reference to save memory.
seems like the most likely explanation. Of course there is no documentation though.

Just to clarify, In the top example, the array doesn't end up getting copied due to the return/assignment?

revmoo
May 25, 2006

#basta
Any time i see pass-by-reference code outside of something like a framework my spider sense goes off.

v1nce
Sep 19, 2004

Plant your brassicas in may and cover them in mulch.

Splinter posted:

Just to clarify, In the top example, the array doesn't end up getting copied due to the return/assignment?
If you're overwriting the same thing you passed-by-reference into the function then the rest of your code probably won't know the difference.
That said, unless you're also returning by reference, you'll get a copy, and it'll eat memory.

Because you're probably not running xdebug yourself, let me show you what's going on here.
code:
function doThing(array $array)
{
    $array[0] = 'X';
    return $array;
}

$src = ['A', 'B', 'C']; // array@424
$srcA = doThing($src); // array@968
$srcA[1] = 'Z'; // array@968

var_dump($src);  // ["A","B","C"]
var_dump($srcA); // ["X","Z","C"]
That's a regular array with no references. The original array is left intact as only a copy was given to doThing.
You can also see the memory address of the variable $srcA (array@968) is different to the memory address for $src (array@424) when the value is returned from doThing(), so it's most definitely a copy.

code:
function doThing(array &$array)
{
    $array[0] = 'Y';
    return $array;
}

$src = ['A', 'B', 'C']; // array@328
$srcA = doThing($src); // array@120
$srcA[1] = 'Z'; // array@120

var_dump($src);  // ["Y","B","C"]
var_dump($srcA); // ["Y","Z","C"]
Here we pass-by-reference. You can see the original array is modified by doThing because it was passed by reference.
But when we get the array back out, it's now a copy at a new memory address.

code:
function &doThing(array &$array)
{
    $array[0] = 'Y';
    return $array;
}

$src = ['A', 'B', 'C']; // array@328
$srcA = doThing($src); // array@328
$srcA[1] = 'Z'; // array@120

var_dump($src);  // ["Y","B","C"]
var_dump($srcA); // ["Y","Z","C"]
Here's half the solution. We're now indicating that our function will return a reference.
Notice the memory address of the variable returned by doThing is the same address as $src. However, also notice as soon as we try to modify that new variable, it turns it into a copy.
That's because we haven't indicated $srcA is a reference binding. It's behaving like a copy but it's being cheaper on memory until we modify it.

code:
function &doThing(array &$array)
{
    $array[0] = 'Y';
    return $array;
}

$src = ['A', 'B', 'C']; // array@328
$srcA = &doThing($src); // array@328
$srcA[1] = 'Z'; // array@328

var_dump($src);  // ["Y","Z","C"]
var_dump($srcA); // ["Y","Z","C"]
Here we finally say that $srcA is a reference binding (=&), so the memory addresses of both $src and $srcA remain the same throughout. No copies.

revmoo posted:

Any time i see pass-by-reference code outside of something like a framework my spider sense goes off.
Pretty much this.

Splinter
Jul 4, 2003
Cowabunga!

I really appreciate the in depth explanation. Thanks! I'll have to checkout xdebug.

spiritual bypass
Feb 19, 2008

Grimey Drawer
I want to understand the performance of my live programs. Are xhprof and xhgui still the standard choice for profiling?

McGlockenshire
Dec 16, 2005

GOLLOCKS!

rt4 posted:

I want to understand the performance of my live programs. Are xhprof and xhgui still the standard choice for profiling?

Yes, but development activity on xhprof seems to have slowed or stopped. There's no sign of it being updated for PHP7 by the maintainers.

v1nce
Sep 19, 2004

Plant your brassicas in may and cover them in mulch.
I'm looking to make Logging easier for my team to use. We're on Symfony2 and passing the logger into everything with DI is a real thorn in everyone's rear end.

We're using a single Monolog logger as a service. I'm thinking of creating a static singleton which gets the Monolog service via DI during boot, and uses the PSR-3 interface, so I'm not expecting any changes.
It'll act like a simple facade for the Monolog class, like this:
code:
final class MyShittyLogger
{
    protected static $logger;

    public static function setLogger($logger)
    {
        self::$logger = $logger;
    }

    public static function log($level, $message, array $context = array())
    {
        return self::$logger->log($level, $message, $context);
    }

    // ...
}
Can anyone think of a reason I shouldn't implement this? I have a nagging feeling I shouldn't, but I can't come up with an actual reason not to.
Most peoples complaints about static/singletons stem from issues with testing, but if we bootstrap the test framework to populate the logger with its own object, then I actually see this as a good thing. It'll let us see any alerts raised during the test execution, and we won't have to inject mocks for Monolog all over the drat place.

bigmandan
Sep 11, 2001

lol internet
College Slice

v1nce posted:

I'm looking to make Logging easier for my team to use. We're on Symfony2 and passing the logger into everything with DI is a real thorn in everyone's rear end.

We're using a single Monolog logger as a service. I'm thinking of creating a static singleton which gets the Monolog service via DI during boot, and uses the PSR-3 interface, so I'm not expecting any changes.
It'll act like a simple facade for the Monolog class, like this:
code:
final class MyShittyLogger
{
    protected static $logger;

    public static function setLogger($logger)
    {
        self::$logger = $logger;
    }

    public static function log($level, $message, array $context = array())
    {
        return self::$logger->log($level, $message, $context);
    }

    // ...
}
Can anyone think of a reason I shouldn't implement this? I have a nagging feeling I shouldn't, but I can't come up with an actual reason not to.
Most peoples complaints about static/singletons stem from issues with testing, but if we bootstrap the test framework to populate the logger with its own object, then I actually see this as a good thing. It'll let us see any alerts raised during the test execution, and we won't have to inject mocks for Monolog all over the drat place.

This may be one of those cases where "breaking the rules" (tight coupling, global state) would be beneficial to you and your team. Logging is one of those things that you need in enough places to warrant this kind of treatment. Definitely go over it with your team though.

Tempus Thales
May 11, 2012

Artwork by Tempus Thales
Can someone PM about Setting Up GoonAuth with Discourse?

The goon auth repo I am using is: https://github.com/LoneBoco/GoonAuth and we are running a Discourse as a forum. Our Goon Dev had some real-life complications and he had to bolt, so it has fallen on my lap to get this up and going, and I said yes because I can't say no to my goon-team and because I figure this would be a good opportunity to learn Laravel.

I have running Discourse of a docker image in a DO droplet. Discourse runs off its own PG db, and from what I have seen the GoonAuth uses LDAP (dunno why) and it should be able to use PG like the forums do. I have been taking a look at the configuration within the GoonAuth. Can GoonAuth run off NGINX or would it be better if it ran on apache2? Do I need to run the Auth from the same server I am running Discourse or can I run it on a separate server and just have ldap running on the server with Discourse?

These are probably stupid questions but I am trying to understand how this works... Some help and advise will be appreciated...

thanks!

Tempus Thales fucked around with this message at 02:05 on Nov 1, 2015

Impotence
Nov 8, 2010
Lipstick Apathy
You can use the Discourse API (generate an admin token from the admin panel) to add a user to a group; grab /users/:username.json to get their user_id, then POST /admin/users/:userid/groups with the data group_id=(goongroupid)

To remove someone from group you can do a single HTTP DELETE /admin/users/:userid/groups/:groupid.

Tempus Thales
May 11, 2012

Artwork by Tempus Thales

Biowarfare posted:

You can use the Discourse API (generate an admin token from the admin panel) to add a user to a group; grab /users/:username.json to get their user_id, then POST /admin/users/:userid/groups with the data group_id=(goongroupid)

To remove someone from group you can do a single HTTP DELETE /admin/users/:userid/groups/:groupid.

I have no clue what that means... Could you be more specific as to where these files I need to edit are located?

Adbot
ADBOT LOVES YOU

Nalin
Sep 29, 2007

Hair Elf

Tempus Thales posted:

Can someone PM about Setting Up GoonAuth with Discourse?

The goon auth repo I am using is: https://github.com/LoneBoco/GoonAuth and we are running a Discourse as a forum. Our Goon Dev had some real-life complications and he had to bolt, so it has fallen on my lap to get this up and going, and I said yes because I can't say no to my goon-team and because I figure this would be a good opportunity to learn Laravel.

I have running Discourse of a docker image in a DO droplet. Discourse runs off its own PG db, and from what I have seen the GoonAuth uses LDAP (dunno why) and it should be able to use PG like the forums do. I have been taking a look at the configuration within the GoonAuth. Can GoonAuth run off NGINX or would it be better if it ran on apache2? Do I need to run the Auth from the same server I am running Discourse or can I run it on a separate server and just have ldap running on the server with Discourse?

These are probably stupid questions but I am trying to understand how this works... Some help and advise will be appreciated...

thanks!

I'm the guy who wrote that branch of GoonAuth. It was designed specifically for the needs of the Goonrathi group. It uses LDAP because we have our forums, mumble, and jabber share the same account information and login. We have no forum integration code because our ipboard forums use LDAP logins. If discourse cannot use LDAP logins, you might want to fork the original repo and build your discourse stuff from there. It won't be easy to remove the LDAP integration from my code.

Biowarfare's post explains that discourse uses a REST api for 3rd party access. You basically use ajax to send get/post/etc http requests to a url. My GoonAuth doesn't have a built in system for doing that. You will have to completely implement that feature.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply