You are not logged in.

Announcement

 Téléchargez la dernière version stable de GLPI      -     Et vous, que pouvez vous faire pour le projet GLPI ? :  Contribuer
 Download last stable version of GLPI                      -     What can you do for GLPI ? :  Contribute

#1 2023-08-28 17:35:28

bado
Member
Registered: 2023-08-28
Posts: 3

GLPI 10.0.9 - API File Upload - No document available

Hi (and greetings)!

I am using GLPI (10.0.9) and want to upload a document with the rest API (and later bind the document to a ticket).
I (somehow) can upload the document, but when I check the uploaded document the GLPI entry is there but the file is not part of it?

Here some informations:

* Currently I am using Postman to upload the files.
   For the upload I enter:
     * A file [C:\temp\test.png]
     * A uploadManifest like this: {"input": {"name": "_Document", "_filename" : {"name":"test.png"}}}
     * I added the Session-Token, App-Token and Accept Headers (and of course the Adress of our GLPI API Endpoint)

What I get as response is this:

{
    "id": 54,
    "message": "Element erfolgreich hinzugefügt: _Document",
    "upload_result": {
        "filename": [
            {
                "name": "test.png",
                "size": 7447,
                "type": "image/png",
                "url": "https://server/files/test.png",
                "deleteUrl": "https://server/apirest.php?filenam=test.png",
                "deleteType": "DELETE",
                "prefix": "test.png",
                "display": "",
                "filesize": "7.27 KB",
                "id": "docfilename166131133"
            }
        ]
    }
}

But when I now check GLPI for Document with ID: 54 I see the Document but without a file.
Image of GLPI


Does anyone have an idea what this can be?
I do not get any error and the only thing I can find in php_errors.log (on the server) is this warning?

[2023-08-28 16:38:07] glpiphplog.WARNING:   *** PHP Warning (2): foreach() argument must be of type array|object, string given in /u01/glpi/html/src/Api/APIRest.php at line 64
  Backtrace :
  src/Api/APIRest.php:127                            Glpi\Api\APIRest->manageUploadedFiles()
  apirest.php:57                                     Glpi\Api\APIRest->call()
  public/index.php:82                                require()

I also have checked the file which is mentioned, it is this function:

/**
     * Upload and validate files from request and append to $this->parameters['input']
     *
     * @return void
     */
    public function manageUploadedFiles()
    {
        foreach (array_keys($_FILES) as $filename) {
           // Randomize files names
            $rand_name = uniqid('', true);
            foreach ($_FILES[$filename]['name'] as &$name) {
                $name = $rand_name . $name;
            }

            $upload_result
            = GLPIUploadHandler::uploadFiles(['name'           => $filename,
                'print_response' => false
            ]);
            foreach ($upload_result as $uresult) {
                 $this->parameters['input']->_filename[] = $uresult[0]->name;
                 $this->parameters['input']->_prefix_filename[] = $uresult[0]->prefix;
            }
            $this->parameters['upload_result'][] = $upload_result;
        }
    }

For me it looks like the function is trying to create a random name for a uploaded file.

best regards

BaDo

Offline

#2 2023-08-29 16:21:03

bado
Member
Registered: 2023-08-28
Posts: 3

Re: GLPI 10.0.9 - API File Upload - No document available

Hi!

I have found a solution for this behaviour and wanted to let you also know (if someone need to know this).

I have debugged the PHP source code, and found the following lines of code in GLPIUploadHandler.php

// clean compute display filesize
        if (isset($response[$pname]) && is_array($response[$pname])) {
            foreach ($response[$pname] as &$val) {
                if (isset($val->error) && file_exists($upload_dir . $val->name)) {
                    unlink($upload_dir . $val->name);
                } else {
                    if (isset($val->name)) {
                        $val->prefix = substr($val->name, 0, 23);
                        $val->display = str_replace($val->prefix, '', $val->name);
                    }
                    if (isset($val->size)) {
                        $val->filesize = Toolbox::getSize($val->size);
                        if (isset($params['showfilesize']) && $params['showfilesize']) {
                            $val->display = sprintf('%1$s %2$s', $val->display, $val->filesize);
                        }
                    }
                }
                $val->id = 'doc' . $params['name'] . mt_rand();
            }
        }

This code tries to get the prefix of the file with this line:

$val->prefix = substr($val->name, 0, 23);

The first 23 characters of the filename will be treated as prefix (even if there is no prefix). So when there is no prefix and your filename is smaller than 23 characters, the filename will be reduced to "" later (because the prefix will be removed).
The reason why there is no prefix, is because we upload only one file with the method I described earlier and the WARNING I also posted in the first post.

The WARNING is triggered by the following line of code in (APIRest.php):

$rand_name = uniqid('', true);

foreach ($_FILES[$filename]['name'] as &$name) {
   $name = $rand_name . $name;
}

The reason is that the foreach needs a array but $_FILES[$filename]['name'] is never an array it is a string (in my opinion)?
I do not know if there is a constelation where $_FILES[$filename]['name'] is no string. But in my case it is definetly just a string. So the foreach will not be executed -> and so the $name variable is not updated with $rand_name . $name.

That is the problem

--- SOLUTION

I now have changed the manageUploadedFiles function in APIRest.php to this:

public function manageUploadedFiles()
    {
        foreach (array_keys($_FILES) as $filename) {
           // Randomize files names
            $rand_name = uniqid('', true);
            
            if( is_array($_FILES[$filename]['name'])) {
            foreach ($_FILES[$filename]['name'] as &$name) {
                $name = $rand_name . $name;
            }} else {
                $name = &$_FILES[$filename]['name'];
                $name = $rand_name . $name;
            }

            $upload_result
            = GLPIUploadHandler::uploadFiles(['name'           => $filename,
                'print_response' => false
            ]);
            foreach ($upload_result as $uresult) {
                 $this->parameters['input']->_filename[] = $uresult[0]->name;
                 $this->parameters['input']->_prefix_filename[] = $uresult[0]->prefix;
            }
            $this->parameters['upload_result'][] = $upload_result;
        }
    }

This function now checks if $_FILES[$filename]['name'] is a array or not (I do not believe this can ever be the case but just to be sure smile). And if it is not an array it writes the random name in the $_FILES[$filename]['name'] variable.


---

With this change the file upload now works for me.


Thank you and have a nice day.

Offline

#3 2023-08-29 20:45:51

cconard96
Moderator
Registered: 2018-07-31
Posts: 2,813
Website

Re: GLPI 10.0.9 - API File Upload - No document available

Can you open a pull request with the changes you made? This would at least start a discussion about this possible fix and possibly the addition to GLPI as a patch for the next version.
https://github.com/glpi-project/glpi/pulls


GLPI Collaborator and Plugin Developer.
My non-English comments are automated translations. Sorry for any confusion that causes.
Mes commentaires non anglais sont des traductions automatiques. Désolé pour toute confusion qui cause.
Mis comentarios que no están en inglés son traducciones automáticas. Perdón por cualquier confusión que cause.

Offline

#4 2023-08-31 11:46:18

bado
Member
Registered: 2023-08-28
Posts: 3

Re: GLPI 10.0.9 - API File Upload - No document available

Hi!
I have created a merge request, thank you and have a nice day.

Offline

Board footer

Powered by FluxBB