Jump to content

Destramic

Members
  • Posts

    969
  • Joined

  • Last visited

Posts posted by Destramic

  1. i've been playing around with nodejs sodium, and im trying to make my js scipt compatable with my php script.  Both are using xchacha20poly1305m but the problem is

    my php encryption looks like this: (whatever it is)

    ��Bd���||�%��AG�wU�Q��[�V���ȷ&6����_�Y:�q��T��X��e"v�

     

    and my js encrption look like that:

    Uint8Array {0: 195, 1: 119, 2: 234, 3: 247, 4: 236…}

     

    theres no way of testing the compatability of both scripts when both encodings differ.

     

    here is my php

    <?php
    
    CONST NONCE_LENGTH = SODIUM_CRYPTO_AEAD_XCHACHA20POLY1305_IETF_NPUBBYTES;
    
    class Sodium
    {
    	private $key;
    	
    	public function __construct(string $key)
    	{
    		if (!extension_loaded('sodium'))
    		{
    		    throw new Exception('Encryption: PHP Sodium extension not found.');
    		}
    		
    	    $key = trim($key);
    
            if (!preg_match('/^[0-9A-Fa-f]{64}+$/', $key))
            {
                throw new Exception('Encryption: Unrecognized key.');
            }
    		
    		$this->key = hex2bin($key);
    	}
    	
    	public function encrypt(string $plaintext)
    	{
    		$nonce = random_bytes(NONCE_LENGTH);
    		
    		$ciphertext = sodium_crypto_aead_xchacha20poly1305_ietf_encrypt(
    		    $plaintext,
    		    null,
    		    $nonce,
    		    $this->key
    		);
    		
    		return $nonce . $ciphertext;
    	}
    	
    	public function decrypt(string $encryption)
    	{
    		if (strlen($encryption) < 24)
    	    {
    	        throw new Exception('Encryption: Unrecognized Encryption.');
    	    }
    	   	    
    		$plaintext = sodium_crypto_aead_xchacha20poly1305_ietf_decrypt(
    		    substr($encryption, 24),
    		    null,
    		    substr($encryption, 0, 24),
    		    $this->key
    		);
    
    		if ($plaintext === false)
    		{
    		    throw new Exception('Encryption: Decryption Failed.');
    		}
    		
    		return $plaintext;
    	}
    }
    
    $sodium = new Sodium('724b092810ec86d7e35c9d067702b31ef90bc43a7b598626749914d6a3e033ed');
    $encryption = $sodium->encrypt('shhh this is a secret');
    echo $encryption;
    echo $sodium->decrypt($encryption);

     

    and you can view the js live here https://codesandbox.io/s/l45orjlnk7

    note: when viewing page you may have to delete a character of the code and replace to see results ?

    or theres a screenshot https://ibb.co/XkcPV4B

     

    i hope you can help with my dilemma

     

    thank you

     

  2. the first select fetches properties from my properties table by thier gas expiry date, ie gas service, which is listed as a pre-task (no property_task entry). when this task is assigned to a trade it will have a property_task_id. so im selecting tasks which exists and dont yet exist for a gas service.

    and the second select will select anything else for that particular deparment. eg. repair on boiler, fire etc.

    it pull all the rows together, giving me the full list of task/pre-tasks for a selected department.

     

  3. thank kicken for seeing my errors, what on earth was i donig with the regex! (head shaking)

    ive made the changes to my query now which gets the users assigned department and task type id's and compares it with the the ids from the appointments

     

    SELECT SUM(task_appointment.count) AS `count`
    FROM ((SELECT COUNT(pt.property_task_id) AS `count`,
    				     p.gas_service_expiry_date AS `priority_date`,
                         d.department_id,
    		             tt.task_type_id,
                         pt.status
                         FROM property_tasks pt
    				     INNER JOIN properties p ON p.property_id = pt.property_id
                         INNER JOIN task_types tt ON tt.task_type_id = pt.task_type_id
                         INNER JOIN trade_task_types ttt ON ttt.task_type_id = tt.task_type_id
                         INNER JOIN trades t ON t.trade_id = ttt.trade_id
                         INNER JOIN departments d ON d.department_id = pt.department_id
                         INNER JOIN property_appointments pa ON pa.property_task_id = pt.property_task_id
                         WHERE tt.task_type = "Gas Service" 
                         AND d.department = "Gas Servicing"
                         AND IF(pa.completed_timestamp, pa.completed_timestamp, pa.end_date) < NOW()
    			)
    UNION ALL
    (SELECT COUNT(pt.property_task_id) AS `count`,
            DATE_FORMAT(DATE_ADD(pt.created_timestamp, INTERVAL pt.priority_days DAY), "%Y-%m-%d") AS `priority_date`,
            d.department_id,
    		tt.task_type_id,
            pt.status 
            FROM property_tasks pt
            INNER JOIN properties p ON p.property_id = pt.property_id
    		INNER JOIN task_types tt ON tt.task_type_id = pt.task_type_id
            INNER JOIN trade_task_types ttt ON ttt.task_type_id = tt.task_type_id
            INNER JOIN trades t ON t.trade_id = ttt.trade_id
            INNER JOIN departments d ON d.department_id = pt.department_id
    		INNER JOIN property_appointments pa ON pa.property_task_id != pt.property_task_id
            WHERE tt.task_type != "Gas Service" 
            AND d.department != "Gas Servicing"
    )) task_appointment
    INNER JOIN (SELECT u.user_id,
                       GROUP_CONCAT(d.department_id) AS `department_ids`,
                       GROUP_CONCAT(tt.task_type_id) AS `task_type_ids`
    		    FROM users u
    			INNER JOIN trade_departments td ON td.user_id = u.user_id
                INNER JOIN departments d ON d.department_id = td.department_id
                INNER JOIN user_trades ut ON ut.user_id = u.user_id
                INNER JOIN trades t ON t.trade_id = ut.trade_id
                INNER JOIN trade_task_types ttt ON ttt.trade_id = t.trade_id
                INNER JOIN task_types tt ON tt.task_type_id = ttt.task_type_id
    ) user
    WHERE status = "Active"
    AND task_appointment.department_id IN (user.department_ids)
    AND task_appointment.task_type_id IN (user.task_type_ids)
    AND user.user_id = 1
    ORDER BY task_appointment.priority_date ASC

     

    it comes back with the correct count which is good...any final thouhts?

     

    thank you again

  4. maybe i should post in the mysql section but i really feel this is a regex issue.

    my query is just to count unallocated/uncompleted tasks and appointments

    here is the query

    SELECT SUM(task_appointment.count) AS `count`
           FROM ((SELECT COUNT(pt.property_task_id) AS `count`,
    				     p.gas_service_expiry_date AS `priority_date`,
                         d.department,
                         GROUP_CONCAT(t.trade) AS `trades`,
                         pt.status
                         FROM property_tasks pt
    				     INNER JOIN properties p ON p.property_id = pt.property_id
                         INNER JOIN task_types tt ON tt.task_type_id = pt.task_type_id
                         INNER JOIN trade_task_types ttt ON ttt.task_type_id = tt.task_type_id
                         INNER JOIN trades t ON t.trade_id = ttt.trade_id
                         INNER JOIN departments d ON d.department_id = pt.department_id
                         INNER JOIN property_appointments pa ON pa.property_task_id = pt.property_task_id
                         AND tt.task_type = "Gas Service" 
                         AND d.department = "Gas Servicing"
                         AND IF(psa.completed_timestamp, psa.completed_timestamp, psa.end_date) < NOW()
    )
    UNION ALL
    (SELECT COUNT(pt.property_task_id) AS `count`,
            DATE_FORMAT(DATE_ADD(pt.created_timestamp, INTERVAL pt.priority_days DAY), "%Y-%m-%d") AS `priority_date`,
            d.department,
    		GROUP_CONCAT(t.trade) AS `trades`,
            pt.status
            FROM property_tasks pt
            INNER JOIN properties p ON p.property_id = pt.property_id
    		INNER JOIN task_types tt ON tt.task_type_id = pt.task_type_id
            INNER JOIN trade_task_types ttt ON ttt.task_type_id = tt.task_type_id
            INNER JOIN trades t ON t.trade_id = ttt.trade_id
            INNER JOIN departments d ON d.department_id = pt.department_id
    		INNER JOIN property_appointments pa ON pa.property_task_id != pt.property_task_id
            AND tt.task_type != "Gas Service" 
            AND d.department != "Gas Servicing"
    )) task_appointment
    INNER JOIN (SELECT GROUP_CONCAT(d.department) AS `departments`,
                       GROUP_CONCAT(t.trade) AS `trades`
    		    FROM users u
    			INNER JOIN trade_departments td ON td.department_id = u.user_id
                INNER JOIN departments d ON d.department_id = td.user_id
                INNER JOIN user_trades ut ON ut.user_id = u.user_id
                INNER JOIN trades t ON t.trade_id = ut.trade_id
    		    WHERE u.user_id = 1
    ) user
    WHERE user.departments REGEXP REPLACE(task_appointment.department, ',', '|') > 0
    AND user.trades REGEXP REPLACE(task_appointment.trades, ',', '|') > 0
    AND status = "Active"
    ORDER BY task_appointment.priority_date ASC

     

    note the unions are almost simular but draw different rows

    1st being gas servicing under certian conditions and 2nd anything else

     

    thank you

  5. i have two CONCAT_GROUPS in my sql query, 1 being the users trades and the other being the trades required for the a particular task.

    What im tyring to do is to find if the user has the correct trade for a particular task.

    here is what ive got so far which does work, but doesnt match the words as i want, for instance if @user_trades = REPLACE('plumb,electrician', ',', '|'), it will still match for plumb

    SELECT @user_trades := REPLACE('plumber,electrician', ',', '|'),   // regex
           @task_trades := 'painter,plumber',   // string
    @task_trades REGEXP @user_trades

    how can i make the regex match a trade 100% or nothing

     

    thank you

  6. i can pass the relevant ID's over infact, i don't know what i didnt do that instead of complicating things!

    the simpliest ways are always the best. :suicide:

    thank you for the insight on how i could of done the query also.

     

  7. im unable to find an example when it comes to select and insert in my particular case, so any help would be greatly appreciated.

    here is my 2 select queries which retrieve the department_id and task_type_id.  what i want to do it is use those two values inside an insert as well as adding additional values.

     

    SELECT department_id FROM departments WHERE department = "Gas Servicing"
    SELECT task_type_id FROM task_Types WHERE task_type = "Gas Service"
    
    INSERT INTO property_appointments (property_id, department_id, task_type_id, notes, priority_days) 
                               VALUES (:property_id, ?, ?, :notes, 1)

     

    is this possible please?

     

    thank you

  8. Beautiful stuff barand, although I've dropped the task statuses and added status, start time stamp and end timestamp to my tasks tablet and did it that way.  

    Ps. I've still used what you've done for me previosuly but adding this will alter task times depending on task start and end, making things more accurate.

    Thank you again for your efforts

  9. i have no idea how to do this in all honesty, hence my post.

    i have a table called task_statuses, which records the statuses and times of a given task,  and those tasks are allocated to an engineer for the day.

    before the engineer is at the task he/she will hit a button called Notify, which will send an sms and email to notify an engineer is on the way....when at the tasks the engineer has 3 further statuses to choose from depending on the outcome of task No Access, Completed or Rearranged.

     

    task statuses
    -------------------------------------------------------------                                                  
                                                           
    Uncommenced                        default (no task status)                                                      
    Notified                           start                                                      
    No Access|Completed|Rearranged     end
    
    -------------------------------------------------------------

    If the engineer has no access at 8am, then there would be 2 statues added.

    1. Notifiied

    2. No Access

     

    now the engineer may try again at 11am.  so before arriving the engineer will click a button called retry which will add Notified to the tasks_statuses and then is able to choose the 2nd outcome of the task

    3. Notifed (Back to square one)

    4. 2nd Outcome (Completed?)

     

    what i want to do is caluclate the complete time spent on the task.

     

    Here is a typical example:

    tt.png.55f03b1f6a5dbe009f59c6c3711e357a.png

    1st attempt: 60 mins

    2nd attempt: 28 mins.

    Total task time : 88 mins

     

    How is this possible please?

    Thank you

     

  10. I've been doing things wrong for years...I've had one model class per controller with multiple methods. Ie. Get tasks, get task etc

    I really do like the structure I've been shown here and I'm excited to make the changes.  Also I will check that link out ignace.

    Thank you all for your help and patience as It means a lot to me to know the correct way of doing things.

     

    ?

     

  11. here is what ive come up with:

     

    <?php
    
    class Validator
    {
        private $entities;
        private $fields;
    
        private $error_messages = array();
    
        public function __construct($entities, array $fields = array())
        {
            if (!is_array($entities))
            {
                $entities = array($entities);
            }
    
            foreach ($entities as $entity)
            {
                $this->check_entity($entity);
            }
    
            $this->entities = $entities;
            $this->fields   = $fields;
        }
    
        private function check_entity($entity)
        {
            if (!is_object($entity))
            {
                throw new Exception('Validator: Entity must be an object.');
            }
    
            return true;
        }
    
        public function validate(array $data, $strict = false)
        {
            foreach ($this->entities as $entity)
            {
                foreach ($data as $property => $value)
                {
                    if (!empty($this->fields) && !in_array($property, $this->fields))
                    {
                        throw new Exception(sprintf('Validator: Unknown field %s', $property));
                    }
    
                    if (!method_exists($entity, $property))
                    {
                        throw new Exception(sprintf('Validator: Unknown method %s', $property));
                    }
    
                    try
                    {
                        $result = $entity->$property($value);
                    }
                    catch (Exception $exception)
                    {
                        if ($strict)
                        {
                            throw new Exception($exception->getMessage());
                        }
                        else
                        {
                            $error_message = ucwords($property) . ': ' . $exception->getMessage();
    
                            $this->error_messages[$property] = $error_message;
                        }
                    }
                }
            }
        }
    
        public function get_error_messages()
        {
            return $this->error_messages;
        }
    
        public function is_valid()
        {
            return empty($this->error_messages);
        }
    }
    
    class Assert
    {
        public function __call(string $constraint, $arguments)
        {
            $class = $constraint;
    
            if (!class_exists($class))
            {
                throw new Exception(sprintf('Assert: Constraint %s doesn\'t exist.', $constraint));
            }
            else if (!method_exists($class, 'assert'))
            {
                throw new Exception(sprintf('Assert: Method assert doesn\'t exist for %s.', $constraint));
            }
    
            return call_user_func_array(array(new $class, 'assert'), $arguments);
        }
    }
    
    class Not_Blank
    {
        public function assert($value)
        {
            if (empty($value))
            {
                throw new Exception('Value is empty');
            }
    
            return true;
        }
    }
    
    class Login extends Assert
    {
        public function username($username)
        {
            $this->not_blank($username);
        }
    
        public function password($password)
        {
            $this->not_blank($password);
        }
    }

     

    form validation:  i added fields to be inputted to make validation stricter, becasue if post data is manipulated and there is no username or post in the data then the validator would return true.

    $validator = new Validator(array(new Login));
    
    $post = array(
        'username' => null,
        'password' => null
    );
    
    // fields added to be validated
    $validator->validate($post, array(
        'username',
        'password'
    ));
    
    if (!$validator->is_valid())
    {
        print_r($validator->get_error_messages());
    }

     

    business model data validation...this is where im able to put validation to strict and it will return exceptions instead of getting friendly error messages

    $validator = new Validator(array(new Login));
    
    // true = exceptions will be returned
    $validator->validate($data, true);

     

    if you could tell me what you think and please elaborate on how form validation and business model validation should work

     

    thank you

  12. im trying to digest everything your saying here...so...

    ok validating a form and returning error messages for a user is great...but for instance, if form data is passed to my business model after being validated would i need to validate the data again in themodel, but this time returning exceptions?

     

     

     

  13. i like the idea of loading a controller view inside of the view it's self. so here it is...

     

    view method 

       public function load($controller, $variables = array())
        {
            $dispatcher = new Dispatcher($this->get_request(), $this->get_response());
    
            if (!$dispatcher->is_dispatchable($controller))
            {
                throw new Exception(sprintf('View: Unable to dispatch %s.', $controller));
            }
            
            if (!empty($variables))
            {
                self::$variables = array_merge(self::$variables, $this->escape_values($variables));
            }
            
            return $dispatcher->dispatch()->get_view()->get_contents();
        }

     

    then in my pages

    echo $this->load('template:common:header', array(
    	'heading'             => 'Task',
        'heading_description' => 'This is a quick view of your current task'
    ));

     

    thank you both for your help :)

  14. Quote

    This comes close to your desired results, although our arithmetic differs

    i just ran the query and seen the figures.  I assumed it was my error and not your query ?

    but it works brillantly...can't thank you enough for your efforts barand.

    thank you!

     

    1 hour ago, Barand said:

    because there is never no empty date for a two week period 

    and i hope not :)

  15. interesting, ok so the user has inputted a date and your checking if the date is >= 18 or  <100 if so then set date and if not it'll throw an exception.

    shouldnt a validation error message go back to the user in the form process? or should i just rely on client side validation for that.

    and if they pass client side validation then exceptions will be thrown if invalid.

     

    i hope you can elaborate on this please.

     

    thank you

  16. a controller for the header sounds good, but leaves me with the question how would i run two controllers or load the header controller into other controllers.

    what would be the best pattern/way please requinix?

     

    thank you for your patience

  17. what im trying to achive to know when there is available slots for a particular employee...in this case a gas engineer.

     

    SELECT scheduled_date,
           username,
           t.time_period,
           am.scheduled_time,
           pm.scheduled_time,
           (SELECT task_time FROM task_types WHERE type = 'Gas Service') AS task_time
           FROM users u
    INNER JOIN user_role_mappings urm ON urm.user_id = u.user_id
    INNER JOIN user_roles ur ON ur.user_role_id = urm.user_id
    INNER JOIN tasks t ON t.user_id = u.user_id
    LEFT JOIN (SELECT t.task_id,
    				  tt.task_time AS `scheduled_time`
                FROM tasks t
                INNER JOIN task_types tt ON tt.task_type_id = t.task_type_id
                WHERE t.time_period = 'AM') AS am ON am.task_id = t.task_id
    LEFT JOIN (SELECT t.task_id,
    				  tt.task_time AS `scheduled_time`
                FROM tasks t
                INNER JOIN task_types tt ON tt.task_type_id = t.task_type_id
                WHERE t.time_period = 'PM') AS pm ON pm.task_id = t.task_id
    WHERE ur.role = 'gas_service_engineer'
    GROUP BY t.time_period
    HAVING ((am.scheduled_time + task_time) < 360 OR (pm.scheduled_time + task_time) < 360)

     

    ive been working on this for 2 nights now and its not returning the exact results.

    my theory is to run this query get the engineers availbility, if theres a slot then book a task to those who are free, based on task time...also i wanted to range dates and get everything inbetwen.

    overall thinking of it i don't need to the whole range of dates, because there is never no empty date for a two week period (so please scrap my first initial post...sorry to have waste your time)

    if i can get this query working then i'll be set.

     

    here is my results

    task2.png

    which dont match the tasks and task times for the particular date

    task1.png

     

    im looking to get there results from my query

    date                    period             scheduled time

    --------------------------------------------------------------------------

    2018-08-21         AM                        180 

    2018-08-21        PM                           60

    2018-09-24        AM                         180

    --------------------------------------------------------------------------

     

    i believe its something wrong with my left joins, but what do i know.

    i hope you can help and point me in the right direction....thank you barand, sorry again

     

     

     

  18. sorry requinix i think i may have no explained myself correcly, although you may understand what ive been trying to say. but i'll explain fully

    heres my layout

     

    tets.png

     

    on the left navigation you will see a count of 5 for the number of tasks.

     

    how my pages are put together

    <?php echo $this->render('header.html'); ?>
    login page
    <?php echo $this->render('footer.html'); ?>

    i could do what you said like so:

    <?php echo $this->render('header.html' array('task_count' => $user_tasks_count)); ?>
    login page
    <?php echo $this->render('footer.html'); ?>

    but this would require me to do this in every controller not just login

        public function login($task_id)
        {
            $user = $this->get_user();
    
    	$this->render(array(
               'user_tasks_count' => $this->tasks->get_tasks_count($user->user_id());
            ));
        }

     

    if this is how it should be done then so be it, just dont seem too practical...sorry to keep on.

     

    ps. feel free to tell me to shut up and move on :)

     

    thank you

     

  19. im trying to get the range of dates from my tasks table,  ranging from current date to the last date...but i also want to get the date even if a result/task doesn't exist

         
    select DISTINCT(CURRENT_DATE()) as today,
    	   scheduled_date, 
          (SELECT scheduled_date + INTERVAL 7 - weekday(scheduled_date) DAY FROM tasks order by scheduled_date desc limit 1) AS last_date
    from tasks
    HAVING today < last_date AND today > scheduled_date

     

    result:

    --------------------------------------------------------------------------

    today                scheduled _date        last_date

    2018-08-23         2018-09-24            2018-10-01

    ------------------------------------------------------------------------

    so i only have 1 result in the table for 2018-09-24

    the last date (2018-10-01) is the next monday from the furthest date 2018-09-24

     

    what im trying to achieve is a range of dates between today and 2018-10-01

    ie.

    2018/09/24

    2018/09/25

    ... etc

    2018-09-30

    2018-10-01

     

     

    thank you guys

         
  20. I'm using my own framework that I built...I think it's pattern issues that I have.

    OK so in a typical page I'll load the header.html and footer.html with my content in between...now my header has a menu and I want to add result counts from my database. My header is also rendered on every page.

    Ie.  Tasks (5)

    Just don't see a clear way of how this should be done.

    How is this typically done in the real world?

    Thank you

  21. That is possible with my view when rendering but still I would need to pass vars on each page which seems unlogical and long winded

    Preloading vars in my bootstrap may be the best way to do this then in my case.

    Thank you

  22. Hey guys I include my header to my pages by adding this to the top of the page

    $this->render ('myheader.html');

    The problem is I want to pass results from my db to the navigation menu, which would require me to assign vars in each controller view that includes the header.

    What is the best way to do this please?

    Another way I can think off is assigning the results to my view in my bootstrap ready for the controllers...but I'm sure there is a more logical way.

    Thank you

     

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.