Only navigator is working inside onTap() of Inkwell

I am listing out notifications. I want to update read status in database when the user clicked on the notification. I used the update function inside the OnTap() function of Inkwell widget, along with navigation to next page. But the async function is not calling. Is there any possible way to solve this issue?

Here is my Code :

class NotificationList extends StatefulWidget {
const NotificationList({Key? key}) : super(key: key);

@override
 _NotificationListState createState() => _NotificationListState();
 }

class _NotificationListState extends State<NotificationList> {
 String useremail = '';
 String appusertype = '';

 Future getList() async {
 SharedPreferences preferences = await SharedPreferences.getInstance();
  setState(() {
  useremail = preferences.getString('useremail') ?? "Not found";

  //debugPrint(useremail);
  // debugPrint(appusertype);
  });

 Map<String, String> headers = {
  'Content-Type': 'application/x-www-form-urlencoded',
  'Charset': 'utf-8'
 };
 Map<String, dynamic> body = {
  "email": useremail,
 };
 var bodyEncoded = body.keys.map((key) => "$key=${body[key]}").join("&");
 //print(bodyEncoded);
 var url = "/notification_list.php";
 var response = await http.post(Uri.parse(ApiConstant.baseUrl + url),
    headers: headers,
    encoding: Encoding.getByName('utf-8'),
    body: bodyEncoded);
 
 return json.decode(response.body);
 }

Future updateStatus(id) async {
 Map<String, String> headers = {
  'Content-Type': 'application/x-www-form-urlencoded',
  'Charset': 'utf-8'
};
Map<String, dynamic> body = {
  "id": id,
};
var bodyEncoded = body.keys.map((key) => "$key=${body[key]}").join("&");
//print(bodyEncoded);
var url = "/update_notification.php";
var response = await http.post(Uri.parse(ApiConstant.baseUrl + url),
    headers: headers,
    encoding: Encoding.getByName('utf-8'),
    body: bodyEncoded);
print(id);
print("object");
return jsonDecode(response.body);
}

@override
void initState() {
super.initState();
// checkLogin();
}

@override
Widget build(BuildContext context) {
 return Scaffold(
    appBar: AppBar(
      backgroundColor: const Color.fromARGB(255, 30, 64, 122),
      title: const Text(
        'Notifications',
        style: TextStyle(color: Colors.orange),
      ),
      centerTitle: true,
      bottom: const PreferredSize(
          preferredSize: Size.zero,
          child: Text(
            "عرض قائمة الممتلكات",
            style: TextStyle(color: Colors.orange),
          )),
    ),
    body: Container(
      decoration: const BoxDecoration(
          image: DecorationImage(
        image: AssetImage("assets/building.jpg"),
        fit: BoxFit.cover,
      )),
      child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: FutureBuilder(
            future: getList(),
            builder: ((context, AsyncSnapshot snapshot) {
              if (snapshot.hasError) print(snapshot.error);
              //print("object");
              if (snapshot.hasData) {
                List list = snapshot.data as List;
                if (list.isEmpty) {
                  return const Center(
                      child: Card(
                          color: Colors.white,
                          child: Padding(
                            padding: EdgeInsets.all(20.0),
                            child: Text('No Notifications yet!'),
                          )));
                }
                return ListView.builder(
                    itemCount: snapshot.data!.length,
                    itemBuilder: ((context, index) {
                      List? list = snapshot.data as List?;
                      return InkWell(
                        onTap: () async {
                          updateStatus(list![index]['id']);
                          print(list[index]['id']);

                          list[index]['title'] == "Interest Request"
                              ? Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                      builder: (context) =>
                                          const InterestRequestList()))
                              : null;
                        },
                        child: Card(
                          color: Colors.white,
                          shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(10)),
                          child: Padding(
                            padding: const EdgeInsets.all(20.0),
                            child: Row(
                              children: [
                                // Container(
                                //   width: 50,
                                //   height: 70,
                                // decoration: const BoxDecoration(
                                //   image: DecorationImage(
                                //               image: AssetImage ("assets/building.jpg"),
                                //               fit:BoxFit.cover,
                                //               )
                                // ),),
                                const Expanded(
                                  flex: 1,
                                  child: Icon(
                                    Icons.notifications,
                                    color: Colors.grey,
                                  ),
                                ),
                                //Spacer(),
                                Expanded(
                                  flex: 5,
                                  child: Padding(
                                    padding: const EdgeInsets.fromLTRB(
                                        10, 0, 0, 0),
                                    child: Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: [
                                          list![index]['read_status'] == '0'
                                              ? Text(
                                                  list[index]['title'],
                                                  style: const TextStyle(
                                                      color: Colors.orange,
                                                      fontSize: 15),
                                                )
                                              : Text(
                                                  list[index]['title'],
                                                  style: const TextStyle(
                                                      color: Colors.orange,
                                                      fontSize: 15),
                                                ),
                                          Text(list[index]['body']),
                                        ]),
                                  ),
                                ),
                                //const Spacer(),

                                const Expanded(
                                    flex: 1,
                                    child: Icon(Icons.arrow_forward_ios)),
                              ],
                            ),
                          ),
                        ),
                      );
                    }));
              }
              return const Center(
                  child: Card(
                      color: Colors.white,
                      child: Padding(
                        padding: EdgeInsets.all(20.0),
                        child: Text('No Notifications yet!'),
                      )));
              // else {
              //   return const Center(
              //     child: CircularProgressIndicator(),
              //   );
              // }
            }),
          )),
    ));
  }
 }

Sort the array with same element at same index PHP

So I have two arrays with some ids. I want to sort the arrays in a way that same value elements in array2 must be at the same index as in array1.
For example:

array1 = ['b','a','c','d'];
array2 = ['d','a','c','b'];

After the sort array2 should become like array1 => ['b','a','c','d']
Is there any function in Php? Thanks in advance 🙂

After sending email to reset password using PHP many info lines appear to user

I am using the code below to send a link to the user email to reset the password, the code works fine and sends the link. The problem is after sending the link the page will show many lines of information and a success message at the end.

What is wrong with the code below to avoid these lines? Here is the code:

<?php
    use PHPMailerPHPMailerPHPMailer;
    use PHPMailerPHPMailerSMTP;
    use PHPMailerPHPMailerException;

    require 'PHPMailer/src/Exception.php';
    require 'PHPMailer/src/PHPMailer.php';
    require 'PHPMailer/src/SMTP.php';

    require 'database.php';

    if(isset($_POST["email"])){
        $emailTo = $_POST["email"];

        $code = uniqid(true);
        $sql = "INSERT INTO reset(code, email) VALUES('$code', '$emailTo');";
        $run = mysqli_query($conn, $sql);
        if(!$run){
            exit("Error");
        }

        $mail = new PHPMailer(true);

        try {
            //Server settings
            $mail->isSMTP();
            $mail->SMTPDebug = 2;
            $mail->Host       = 'smtp.gmail.com';
            $mail->SMTPAuth   = true;
            $mail->Username   = 'myEmail.com';
            $mail->Password   = 'xxxxxxxxx';
            $mail->SMTPSecure = 'tls';
            $mail->Port       = 587;

            //Recipients
            $mail->setFrom('myqmial.com', 'Hello');
            $mail->addAddress($emailTo);
            $mail->addReplyTo('[email protected]', 'No reply');

            // Content
            $url = "http://" .$_SERVER["HTTP_HOST"] . dirname($_SERVER["PHP_SELF"]) . "/resetPassword.php?code=$code";
            $mail->isHTML(true);
            $mail->Subject = 'Reset Password';
            $mail->Body    = "<h1>You asked to reset your password، </h1>
                                Click <a href='$url'>this link</a> Please click on the link";
            $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

            $mail->send();
            echo 'The link has been successfully sent to your email';
            
        } 
        catch (Exception $e) {
            echo "Message could not be sent. Mail Error: {$mail->ErrorInfo}";
        }
        exit();
    }
    
?> 
<form method='POST'>
    <input type='text' name='email' placeholder='Email'>
    <input type='submit' name='submit' value='Reset password'>
</form>

I am attaching an image with the results:
enter image description here

I do not know what mistake I am doing, so how can I just show the message (The link has been successfully sent to your email) without all these lines?

Heroku / PHP / MVC > Requested URL not found

I have a very simple MVC project (no DB) that works very well when I launch it with a local server (“php -S localhost:8000 -t public”).

I use my routing this way:

require "Controllers/AppController.php";

$parsed_url = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$appController = new AppController();

switch ($parsed_url) {
    case '/':
    case '/home':
        $appController->home();
        break;
    case '/about':
        $appController->about();
        break;
    case '/achievements':
        $appController->achievements();
        break;
    case '/contacts':
        $appController->contacts();
        break;
    default:
        $appController->pageNotFound();

I deployed it with Heroku, adding a Procfile, as specified in the official documentation, but now I can only get the homepage of my portfolio. All my other links throw me a “Not Found – The requested URL was not found on this server.”.

Here’s my Heroku log, if that can help:

2022-10-30T09:26:48.666806+00:00 heroku[router]: at=info method=GET path="/about" host=alexis-boucherie-devweb.herokuapp.com request_id=0dd695f8-8252-4cd4-8d3d-e012daf06130 fwd="86.213.16.43" dyno=web.1 connect=0ms service=1ms status=404 bytes=360 protocol=https

What I don’t understand, is that if I try to var_dump my “$parsed_url”, it does return a “/”, for the homepage. So I think it means the program goes through my Switch Case and that my Controller is ok. Also, because I have my homepage showing in the first place.

I tried to modify the page my $appController object calls for, and by doing so, I can access another page. But then again, if I click on any link or manually type the address of one of my pages (for instance “/contacts”), it doesn’t work.

In the end, I tried and searched for other topics related to this, found two here on StackOverflow, about adding an .htacess file, but I’m not sure I’m getting how that really works. Could this be the real source of my problem?

Remove extra generated td values from the table

I’m trying to fill table with values which I’m getting from the database but when I loop though array some values are getting out of the table.

DB values image:
enter image description here

DB structure with dump:
https://www.db-fiddle.com/f/9gTDRBFnguHtagJC4YNnRg/5

Code:

$query = "SELECT * FROM monthly_report";
$result = $this->db->query($query)->result_array();

$data['data'] = $result;
<table class="table table-hover table-striped">
    <thead>
        <tr>
            <th style="text-align:center;">Month</th>
            <th style="text-align:center;">Total Register</th>
            <th style="text-align:center;">January</th>
            <th style="text-align:center;">February</th>
            <th style="text-align:center;">March</th>
            <th style="text-align:center;">April</th>
            <th style="text-align:center;">May</th>
            <th style="text-align:center;">June</th>
            <th style="text-align:center;">July</th>
            <th style="text-align:center;">August</th>
            <th style="text-align:center;">September</th>
            <th style="text-align:center;">October</th>
            <th style="text-align:center;">November</th>
            <th style="text-align:center;">December</th>
        </tr>
    </thead>

    <tbody>
        <?php
        $num = 0;
        for ($m = 1; $m <= 12; $m++) {
            $month = date('F', mktime(0, 0, 0, $m, 1, date('Y')));
            echo "<tr style='text-align:center;'>";
            echo "<td>" . $month . "</td>";


            $short_month_name = date('M', strtotime("2022-$m-01"));

            if (isset($data[$num]['month']) && $data[$num]['month'] == $short_month_name) {

                $decode_data = json_decode($data[$num]['data'], true);
                $decode_isset = isset($decode_data[$short_month_name]) ? $decode_data[$short_month_name] : '';

                echo "<td>" .  $decode_isset . "</td>";
            }

            $num_1 = 0;
            for ($day = 1; $day <= 12; $day++) {

                $short_month_name_1 = date('M', strtotime("2022-$day-01"));

                if (isset($data[$num]['month']) && $data[$num]['month'] == $short_month_name_1) {

                    $decode_data_1 = json_decode($data[$num]['data'], true);
                    $decode_isset_1 = isset($decode_data_1) ? $decode_data_1 : [];

                    foreach ($decode_isset_1 as $v) {

                        if (!empty($v)) {
                            echo "<td>" .  $v . "</td>";
                        } else {
                            echo "<td>0</td>";
                        }
                    }
                } else {
                    echo "<td>0</td>";
                }

                $num_1++;
            }

            echo "</tr>";
            $num++;
        }
        ?>
    </tbody>
</table>

And output is:

enter image description here

I want to remove extra generated td (Marked in red box).

POST an array multidimensional of objects

Submitting for booked time. Add 5 variable at once. Each time has idVenue, idField, date, time and price.

Question: How can we get all of the times selected in an array of arrays?

booked[0] => Array (
  ["idVenue"] => "id Venue",
  ["idField"] => "id Field",
  ["date"] => "date selected",
  ["time"] => "time selected",
  ["price"] => "price selected"
),
booked[1] => Array (
  ["idVenue"] => "id Venue",
  ["idField"] => "id Field",
  ["date"] => "date selected",
  ["time"] => "time selected",
  ["price"] => "price selected"
), 
... 

Code

<input type="hidden" name="idVenue" value="<?=$getTimes['idVenue']?>">
<input type="hidden" name="idField" value="<?=$getTimes['idField']?>">
<input type="hidden" name="date" value="<?=date('Y-m-d',strtotime($getTimes['date']));?>">
<input type="hidden" name="price" value="<?=$getTimes['price']?>">
<input name="time" value="<?=$getTimes['start']?>" type="checkbox">

example
enter image description here

selected 4 nov but the result of values array is always like this

enter image description here

and my goals if selected item and send it to post php and array showed selected value

Exception: Class Not Found in PHP

I get the error:

Exception – Class ‘sitesoutputtab_gamify’ not found when load an edit page.

I have a file named sites/classes/output/edit.php with something like:

<?php

namespace sitesoutput;

class edit extends tabs {

      public function __construct(array $attributes = []) {
             parent::__construct($attributes);

             ...
             ...
             $this->add_tab(new tab_gamify($attributes));
      }

}

And a file named sites/classes/output/tab_gamify.php with something like:

<?php

namespace sitesoutput;

class tab_gamify extends tab {
      ...
      ...
}

I get the previous error message and and i not able to locate my error. Any suggestion or clue will be very appreciated.

Thanks in advance for your time.

I’ve revised namespaces, also reloaded and restarted docker container.

How the primitive type ‘String’ is implemented in PHP? Which character encoding does PHP use? Explain with suitable and easy to understand example

Today, I was trying to understand how the primitive type ‘String’ is implemented in PHP. In search of the same I come across following text from the PHP Manual

The string in PHP is implemented as an array of bytes and an integer
indicating the length of the buffer. It has no information about how
those bytes translate to characters, leaving that task to the
programmer. There are no limitations on the values the string can be
composed of; in particular, bytes with value 0 (“NUL bytes”) are
allowed anywhere in the string (however, a few functions, said in this
manual not to be “binary safe”, may hand off the strings to libraries
that ignore data after a NUL byte.)

After reading above text from the PHP Manual following questions come to my mind :

  1. What does it actually mean by an array of bytes and an integer indicating the length of the buffer? What does actually mean by the term ‘buffer’ in this case?

  2. Why does PHP not handle the task of translating those bytes to characters by itself? Why and what programmer supposed to do in this case of translation?

  3. According to the PHP Manual, there are no limitations on the values the string can be composed of. Does it mean that PHP uses Unicode(utf-8) for the purpose of character encoding?

  4. Do string and byte(a unit of digital information that most commonly consists of eight bits) mean the same thing in PHP?

Someone please clear my above doubts with the help of suitable and easy to understand example/s.

Thank You.

How do I send mail using a php contact form? [duplicate]

So this contact form used to work, however now it loads and says mail sent when someone clicks submit but I never get any emails, what am I missing out?

<?php

// Replace this with your own email address
$siteOwnersEmail = '[email protected]';


if($_POST) {

   $name = trim(stripslashes($_POST['contactName']));
   $email = trim(stripslashes($_POST['contactEmail']));
   $subject = trim(stripslashes($_POST['contactSubject']));
   $contact_message = trim(stripslashes($_POST['contactMessage']));

   // Check Name
    if (strlen($name) < 2) {
        $error['name'] = "Please enter your name.";
    }
    // Check Email
    if (!preg_match('/^[a-z0-9&'.-_+]+@[a-z0-9-]+.([a-z0-9-]+.)*+[a-z]{2}/is', $email)) {
        $error['email'] = "Please enter a valid email address.";
    }
    // Check Message
    if (strlen($contact_message) < 15) {
        $error['message'] = "Please enter your message. It should have at least 15 characters.";
    }
   // Subject
    if ($subject == '') { $subject = "Contact Form Submission"; }


   // Set Message
   $message .= "Email from: " . $name . "<br />";
    $message .= "Email address: " . $email . "<br />";
   $message .= "Message: <br />";
   $message .= $contact_message;
   $message .= "<br /> ----- <br /> This email was sent from your site's contact form. <br />";

   // Set From: header
   $from =  $name . " <" . $email . ">";

   // Email Headers
    $headers = "From: " . $from . "rn";
    $headers .= "Reply-To: ". $email . "rn";
    $headers .= "MIME-Version: 1.0rn";
    $headers .= "Content-Type: text/html; charset=ISO-8859-1rn";


   if (!$error) {

      ini_set("sendmail_from", $siteOwnersEmail); // for windows server
      $mail = mail($siteOwnersEmail, $subject, $message, $headers);

        if ($mail) { echo "OK"; }
      else { echo "Something went wrong. Please try again."; }

    } # end if - no validation error

    else {

        $response = (isset($error['name'])) ? $error['name'] . "<br /> n" : null;
        $response .= (isset($error['email'])) ? $error['email'] . "<br /> n" : null;
        $response .= (isset($error['message'])) ? $error['message'] . "<br />" : null;

        echo $response;

    } # end if - there was a validation error

}

?>
 

And this is the contact form:

<form name="contactForm" id="contactForm" method="post" action="mail/mail.php">
                <fieldset>

                   <div class="form-field">
                           <input name="contactName" type="text" id="contactName" placeholder="Name" value="" minlength="2" required="">
                   </div>
                   <div class="form-field">
                       <input name="contactEmail" type="email" id="contactEmail" placeholder="Email" value="" required="">
                   </div>
                   <div class="form-field">
                           <input name="contactSubject" type="text" id="contactSubject" placeholder="Subject" value="">
                   </div>
                   <div class="form-field">
                        <textarea name="contactMessage" id="contactMessage" placeholder="message" rows="10" cols="50" required=""></textarea>
                   </div>
                  <div class="form-field">
                      <button type="submit" name="submit" value="send"class="submitform">Submit</button>
                      <div id="submit-loader">
                         <div class="text-loader">Sending...</div>
                              <div class="s-loader">
                                    <div class="bounce1"></div>
                                    <div class="bounce2"></div>
                                    <div class="bounce3"></div>
                                </div>
                            </div>
                   </div>

                </fieldset>
            </form>

All the messages work, am I missing out on some SMPT information or something? Are there any alternatives to using phpmailer for this job?

how upload capture image file to sever in java script html php

i working on a project where user capture photo from camera and show capture photo, but I want upload That Photo to server . How we can upload that image file to server . i am new please help me.
please help me how we upload image file to server. i Tried much but can not upload successfully.

<html>
<head>
<title>NigraniSof</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no">

</head>

<body>

<button id="start-camera">Start Camera</button>
<video id="video" width="320" height="240" autoplay></video>
<button id="click-photo">Click Photo</button>
<div id="dataurl-container">
    <canvas id="canvas" width="320" height="240"></canvas>
    <div id="dataurl-header">Image Data URL</div>
    <textarea id="dataurl" readonly></textarea>
</div>

<script>

let camera_button = document.querySelector("#start-camera");
let video = document.querySelector("#video");
let click_button = document.querySelector("#click-photo");
let canvas = document.querySelector("#canvas");
let dataurl = document.querySelector("#dataurl");
let dataurl_container = document.querySelector("#dataurl-container");

camera_button.addEventListener('click', async function() {
    let stream = null;

    try {
        stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: false });
    }
    catch(error) {
        alert(error.message);
        return;
    }

    video.srcObject = stream;

    video.style.display = 'block';
    camera_button.style.display = 'none';
    click_button.style.display = 'block';
});

click_button.addEventListener('click', function() {
    canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
    let image_data_url = canvas.toDataURL('image/jpeg');
    
    dataurl.value = image_data_url;
    dataurl_container.style.display = 'block';
});

</script>  

</body>
</html>

List files from a directory or folder

Problem listing files from a directory

I am trying to list files in a directory I names jss by putting an index.php script in the same folder.
Unfortunately, I have not been able to succeed in doing this but got the error messages shared below after the main
Here is the error I got:
Warning : Undefined array key “submit digitallib/classnotes/jss/” in C:xampphtdocsdigitallibclassnotesjssindex.php on line 2

Warning : opendir(digitallib/classnotes/jss/): The system cannot find the path specifi (code: 3) in C:xampphtdocsdigitallibclassnotesjssindex.php on line 13

Warning : opendir(digitallib/classnotes/jss/): Failed to open directory: No such file or directory in C:xampphtdocsdigitallibclassnotesjssindex.php on line 13

Fatal error : Uncaught TypeError: readdir(): Argument #1 ($dir_handle) must be of type resource or null, bool given in C:xampphtdocsdigitallibclassnotesjssindex.php:15 Stack trace: #0 C:xampphtdocsdigitallibclassnotesjssindex.php(15): readdir(false) #1 {main} thrown in C:xampphtdocsdigitallibclassnotesjssindex.php on line 15

The code I used can be found here:
https://docs.google.com/document/d/1KPmxhN8Z7X6Y7xhqZYC7yDAGU_v-r4sUDcPMmnbSMdY/edit?usp=sharing

How do I protect my Vue-routes with Laravel sanctum

I have a Laravel backend and a Vue frontend. I wanted to know how to protect my Vue routes with Lravael sanctum. I want that only logged in users can see the page?

I have tried this but it did not work: https://medium.com/@AshJuventino/building-a-vue-spa-protected-by-laravel-sanctum-33c9c87cc057 and https://techvblogs.com/blog/spa-authentication-laravel-sanctum-vuejs
vue-router

import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import("../views/Home")
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import("../views/Register")
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import("../views/Login")
  },
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

export default router

api-route-laravel

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

I have tried this but it did not work: https://medium.com/@AshJuventino/building-a-vue-spa-protected-by-laravel-sanctum-33c9c87cc057

https://techvblogs.com/blog/spa-authentication-laravel-sanctum-vuejs

Codeigniter A PHP Error was encountered – Trying to access array offset on value of type null

A PHP Error was encountered
Severity: Notice

Message: Trying to access array offset on value of type null

Filename: helpers/common_helper.php

Line Number: 35

Backtrace:

File: F:xampphtdocssdpnew1applicationhelperscommon_helper.php
Line: 35
Function: _error_handler

File: F:xampphtdocssdpnew1applicationcontrollersadminUsers.php
Line: 36
Function: get_admin_name

File: F:xampphtdocssdpnew1index.php
Line: 315
Function: require_once

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
// -----------------------------------------------------------------------------
// Get Language by ID
function get_lang_name_by_id($id)
{
    $ci = & get_instance();
    $ci->db->where('id',$id);
    return $ci->db->get('ci_language')->row_array()['name'];
}

// -----------------------------------------------------------------------------
// Get Language Short Code
function get_lang_short_code($id)
{
    $ci = & get_instance();
    $ci->db->where('id',$id);
    return $ci->db->get('ci_language')->row_array()['short_name'];
}

// -----------------------------------------------------------------------------
// Get Language List
function get_language_list()
{
    $ci = & get_instance();
    $ci->db->where('status',1);
    return $ci->db->get('ci_language')->result_array();
}

// -----------------------------------------------------------------------------
// Get Admin name by ID
function get_admin_name($id)
{
    $ci = & get_instance();
    $ci->db->where('user_id',$id);
    $ret = $ci->db->get('ci_users')->row_array()['username']; // Problem area 
    if($ret === null || trim($ret) === '') //DH in case of the 'creator' has been deleted
        return 'Unknown';
    return $ret;
}

// -----------------------------------------------------------------------------
// Get country list
function get_country_list()
{
    $ci = & get_instance();
    return $ci->db->get('ci_countries')->result_array();
}

// -----------------------------------------------------------------------------
// Get country name by ID
function get_country_name($id)
{
    $ci = & get_instance();
    return $ci->db->get_where('ci_countries', array('id' => $id))->row_array()['name'];
}

// -----------------------------------------------------------------------------
// Get City ID by Name
function get_country_id($title)
{
    $ci = & get_instance();
    return $ci->db->get_where('ci_countries', array('slug' => $title))->row_array()['id'];
}

// -----------------------------------------------------------------------------
// Get country slug
function get_country_slug($id)
{
    $ci = & get_instance();
    return $ci->db->get_where('ci_countries', array('id' => $id))->row_array()['slug'];
}

// -----------------------------------------------------------------------------
// Get country's states
function get_country_states($country_id)
{
    $ci = & get_instance();
    return $ci->db->select('*')->where('country_id',$country_id)->get('ci_states')->result_array();
}

// -----------------------------------------------------------------------------
// Get state's cities
function get_state_cities($state_id)
{
    $ci = & get_instance();
    return $ci->db->select('*')->where('state_id',$state_id)->get('ci_cities')->result_array();
}

// Get state name by ID
function get_state_name($id)
{
    $ci = & get_instance();
    return $ci->db->get_where('ci_states', array('id' => $id))->row_array()['name'];
}

// -----------------------------------------------------------------------------
// Get city name by ID
function get_city_name($id)
{
    $ci = & get_instance();
    return $ci->db->get_where('ci_cities', array('id' => $id))->row_array()['name'];
}

// -----------------------------------------------------------------------------
// Get city ID by title
function get_city_slug($id)
{
    $ci = & get_instance();
    return $ci->db->get_where('ci_cities', array('id' => $id))->row_array()['slug'];
}

/**
 * Generic function which returns the translation of input label in currently loaded language of user
 * @param $string
 * @return mixed
 */
function trans($string) //DH modif
{
    $ci =& get_instance();
    // return $ci->lang->line($string); //DH : original line

    $tmp = $ci->lang->line($string);
    if( !empty($tmp) )
        return $tmp;
    return '!'. $string . '!';
}