#StackBounty: #php #imagemagick #mediawiki Resize images upon upload in Mediawiki

Bounty: 100

I am ideally after resizing and setting a maxWidth and maxHeight on all my image uploads to mediawiki.

Having looked through the documentation of various different pages in mediawiki I am unable to find anything that says you can edit in anyway images uploaded to a site built on mediaWiki

I have no problem in writing some custom PHP but truth is I have no idea where to start looking in mediaWiki.

My thoughts are: imagemagick similarly to this:

I think you need the > flag on the resize:

convert -size 300x200 xc:red   small.png
convert -size 1000x500 xc:blue large.png
Now convert them both to 800x600 with no flags:

convert small.png -resize 800x600 a.png   # 800x533
convert large.png -resize 800x600 b.png   # 800x400
Now with flags:

convert small.png -resize 800x600> a.png # 300x200
convert large.png -resize 800x600> b.png # 800x400

But again, I cannot see where you would run this after an image upload to change the files dimensions.

Any help would be fantastic.


Get this bounty!!!

#StackBounty: #php #design-patterns #orm #repository #datamapper Why bother with repositories

Bounty: 50

I feel a bit stupid asking this question since there are a lot of resources talking and explaining mappers and repositories but I can’t seem to get my head around it. So I’ve created some example code to explain my confusion. Please note that I don’t know if this code would actually work I wrote this as an example.

This would be the entity / class (Quote.php)

class Quote {
  private $id;
  private $author;
  private $content;

  public function getId() {
    return $this->id;
  }

  public function getAuthor() {
    return $this->author;
  }

  public function getContent() {
    return $this->content;
  }

  public function setId(int $id) {
    $this->id = $id;
  }

  public function getAuthor(string $author) {
    $this->author = $author;
  }

  public function setContent(string $content) {
    $this->content = $content;
  }
}

And this would be the mapper (QuoteMapper.php)

class QuoteMapper {
  private $PDO;

  public function __construct(PDO $PDO) {
    $this->PDO = $PDO;
  }

  public function find(int $id = null, string $search = null) {
    if (!empty($id) && !empty($search)) {
      //Search for id and search word
      $stmt = $this->PDO->prepare("SELECT `id`, `author`, `content` FROM `quotes` WHERE `id` = :id AND `content` LIKE :search LIMIT 1");
      $stmt->bindParam('search', $search, PDO::PARAM_INT);
      $stmt->bindParam('id', $id, PDO::PARAM_INT);
    else if (!empty($id)) {
      //search for id only
      $stmt = $this->PDO->prepare("SELECT `id`, `author`, `content` FROM `quotes` WHERE `id` = :id AND `content` LIKE :search LIMIT 1");
      $stmt->bindParam('id', $id, PDO::PARAM_INT);
    } else if (!empty($search)) {
      //search for search word only
      $stmt = $this->PDO->prepare("SELECT `id`, `author`, `content` FROM `quotes` WHERE `id` = :id AND `content` LIKE :search LIMIT 1");
      $stmt->bindParam('search', $search, PDO::PARAM_INT);
    }

    $stmt->execute();

    $stmt->bindColumn('id', $id);
    $stmt->bindColumn('author', $author);
    $stmt->bindColumn('content', $content);
    $stmt->fetch();

    $quote = new Image();
    $quote->setId($title);
    $quote->setAuthor($source);
    $quote->setContent($alternative);

    return $image;
  }

  public function save(Quote $quote) {
    //A save function
  }

  public function delete(Quote $quote) {
    //A delete function
  }
}

Last but not least, this would be the repository (QuoteRepository.php)

class ArticleRepository {
  private $articleMapper;

  public function __construct(ArticleMapper $articleMapper) {
    $this->articleMapper = $articleMapper;
  }

  public function find(int $id = null, string $search = null) {
    $article = $this->articleMapper->find($id, $search);
    return $article;
  }

  public function save(Quote $quote) {
    $this->articleMapper->save($user);
  }

  public function delete(Quote $quote) {
    $this->articleMapper->delete($user);
  }
}

As I understand my mapper isn’t ‘wrong’ since the purpose of the mapper is to do things such as get and set data from persistent data storage (such as MySQL)

A Data Mapper is a Data Access Layer that performs bidirectional
transfer of data between a persistent data store (often a relational
database) and an in-memory data representation (the domain layer).
From Wikipedia

But my repository doesn’t actually do anything. It just passes the function call along to the mapper? So I can only assume that my mapper contains code that should be in the repository, but what code would that be? Or perhaps I’ve completely misunderstood how data mappers and repositories would work together.

If there are any other things that I have done that are wrong or considered bad practice I would like to hear it. I’m really trying to figure this out! 🙂


Get this bounty!!!

#StackBounty: #php #swagger #openapi #swagger-php #swagger-3.0 Serialize nested properties as form-data with swagger-php

Bounty: 50

This is how Encoding Object Example is done in OpenApi
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md

requestBody:
  content:
    multipart/mixed:
      schema:
        type: object
        properties:
          id:
            # default is text/plain
            type: string
            format: uuid
          address:
            # default is application/json
            type: object
            properties: {}
          historyMetadata:
            # need to declare XML format!
            description: metadata in XML format
            type: object
            properties: {}
          profileImage:
            # default is application/octet-stream, need to declare an image type only!
            type: string
            format: binary
      encoding:
        historyMetadata:
          # require XML Content-Type in utf-8 encoding
          contentType: application/xml; charset=utf-8
        profileImage:
          # only accept png/jpeg
          contentType: image/png, image/jpeg
          headers:
            X-Rate-Limit-Limit:
              description: The number of allowed requests in the current period
              schema:
                type: integer

I’m trying to achive the same thing but with swagger-php.
What I don’t know is how to pass encodings in @OAMediaType to encode the test property as multipart/form-data because by default is encoded as application/json

EX:

 * @OAPost(
 *     path="/admin/test",
 *     summary="Create new Test",
 *     description="Will attempt to create a new Test",
 *     tags={"Admin Test"},
 *     @OARequestBody(
 *          @OAMediaType(
 *              mediaType="multipart/form-data",
 *              encoding={}
 *              @OASchema(
 *                  type="object",
 *                  @OAProperty(
 *                      property="test",
 *                      type="object",
 *                      description="test"
 *                      ref="#/components/schemas/MyTestSchema"
 *                  )
 *              )
 *      )

They have some examples here:

https://github.com/zircote/swagger-php/tree/master/Examples

but I didn’t found any example regarding encoding

Inside here the field is defined
https://github.com/zircote/swagger-php/blob/master/src/Annotations/MediaType.php

   /**
     * A map between a property name and its encoding information.
     * The key, being the property name, must exist in the schema as a property.
     * The encoding object shall only apply to requestBody objects when the media type is multipart or application/x-www-form-urlencoded.
     */
    public $encoding = UNDEFINED;

I’ve tried encoding={"recommended"={"contentType"="multipart/form-data"}} but it’s useless.


Get this bounty!!!

#StackBounty: #php #mysql #mysqli #ms-word Error when generating Word file with multi rows

Bounty: 100

I am trying to SELECT data from my database and show the data in a Word (DOCX) file.

I am working with two type of data.

The first type is data that I want to show once. Like the customer name.

The second type of data is data that is imported with a dynamic row script. The data in my database looks like:
Lines:

-----------------------------------------
| internal_id | quantity | product_name |
|      1      |     1    |     One      |
|      1      |     5    |     Two      |
|      1      |     4    |    Three     |
|      1      |     2    |     Four     |
|      1      |     6    |     Five     |
-----------------------------------------

In my Word template I defined these rows as follow:

{name}
{address}
{lines}
{quantity}
{product_name}
{/lines}

When I execute my script I get the following data in my Word file:

Name
Address 123
{!404_DOCXTemplate_quantity}
{!404_DOCXTemplate_product_name}

Does someone know why the multi row part of my code is not working?

Here is my PHP script where I am selecting the data and generate the Word file:

$result1 = mysqli_fetch_assoc($res1) ;
$link2 = mysqli_connect("localhost", "root", "pass", "db");

if($link2 === false){
  die("ERROR: Could not connect. " . mysqli_connect_error());
}

$sql2 = "SELECT * FROM lines WHERE internal_id = '1'";
$res2 = mysqli_query($link2, $sql2) ;

$result2 = $link2->query($sql2);
if ($result2->num_rows > 0) {
$result2 = mysqli_fetch_assoc($res2) ;

  include_once('./docxtemplate.class.php');

  $docx = new DOCXTemplate('template.docx');

  $docx->set('name', "" . $result1['name'] . "");
  $docx->set('address', "" . $result1['address'] . "");

  $docx->set('LINES', mysqli_num_rows($result2));
  while ($row = mysql_fetch_array($result2))
    {
      $docx->set('quantity', "" . $result2['quantity'] . "");
      $docx->set('product_name', "" . $result2['product_name'] . "");
    }
  $docx->saveAs('test.docx');

  header("Content-Type:application/msword");
  header("Content-Disposition: attachment;filename=test.docx");

  readfile('test.docx');

}

The following function is generating the text !404_DOCXTemplate_
docxtemplate.class.php

private function _parse() {
    if ($doc = $this->getEntryData( 'word/document.xml' )) {
        if (preg_match_all('/{[^}]+}/', $doc, $m )) {
            foreach( $m[0] as $v ) {
                $var = preg_replace('/[s{}]/','', strip_tags( $v ));
                if (isset( $this->data[ $var ] )) {
                    if (is_scalar( $this->data[ $var ] ))
                        $doc = str_replace( $v, $this->_esc( $this->data[ $var ] ), $doc );
                } else {
                    $doc = str_replace( $v, '{!404_'.__CLASS__.'_'.$var.'}', $doc );
                }
            }
        }
        $this->setEntryData( 'word/document.xml', $doc );
        return true;
    } else 
        return false;
}


Get this bounty!!!

#StackBounty: #php #snap #udev #syslog snapd udevmon.go:184: udev monitor observed remove event for unknown device

Bounty: 50

I’m seeing these messages in the syslog on 18.10. How can I fix this? I’ve searched around and not found any solutions.
The two entries that occur approx. every hour in syslog are:

snapd[1893]: udevmon.go:184: udev monitor observed remove event for unknown device "/sys/dentry(3271:phpsessionclean.service)"

snapd[1893]: udevmon.go:184: udev monitor observed remove event for unknown device "/sys/proc_inode_cache(3279:phpsessionclean.service)"

Output:

$ dpkg -S phpsessionclean.service
php-common: /lib/systemd/system/phpsessionclean.service

Output:

$ dpkg -S udevmon.go
dpkg-query: no path found matching pattern *udevmon.go*


Get this bounty!!!

#StackBounty: #php #angularjs #post #mysqli #http-post How do I properly use AngularJS $http.post to update MySQLi table through PHP?

Bounty: 50

I want to update a MySQLi table achievements through PHP. The app is coded in AngularJS and measures various statistics. When a goal is met, I send the information to a PHP script using AngularJS’s $http.post. PHP should then handle the information and update my table accordingly. The $http.post returns a success message, but the table is not updated. I am confident the database connection info is correct.

My AngularJS $scope.updatePhp function using $http.post:

$scope.updatePhp = function(table, column, value, whereColumn, whereValue) {
    $http.post(
        "update-data.php", {
            'table': table,
            'column': column,
            'value': value,
            'whereColumn': whereColumn,
            'whereValue': whereValue
        }
    );
}

My AngularJS $scope.updatePhp function without using the .post shortcut:

$scope.updatePhp = function(table, column, value, whereColumn, whereValue) {

    console.log("Updating. Table: " + table + ", column: " + column + ", value: " + value + ", where: " + whereColumn + ", whereValue: " + whereValue);

    $http({
        method: 'POST',
        url: 'update-data.php',
        data: $.param({ table: table.toString(), column: column.toString(), value: value.toString(), whereColumn: whereColumn.toString(), whereValue: whereValue.toString() }),
        headers: { 'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8' } 
    }).then(function successCallback(response) {
        console.log("Success.");
    }, function errorCallback(response) {
        console.log("Error.");
    });

}

My entire PHP file ‘update-data.php`:

<?php

    //CORS header stuff
    header("Access-Control-Allow-Origin: *");

    //PHP posted info
    $info = json_decode(file_get_contents('php://input'), true);

    //Update the table
    $hostname_DB = "databaseHost";
    $database_DB = "databaseName";
    $username_DB = "databaseUser";
    $password_DB = "databasePass";
    $portnum_DB = "databasePort";
    $mysqli = mysqli_connect($hostname_DB, $username_DB, $password_DB, $database_DB, $portnum_DB ) or die(mysqli_error());

    $table = $info->table;
    $column = $info->column;
    $value = $info->value;
    $whereColumn = $info->whereColumn;
    $whereValue = $info->whereValue;

    $query = "UPDATE '$table' SET '$column' = '$value' WHERE '$whereColumn' = '$whereValue' ";
    $mysqli->query($query) or die(mysqli_error());  

?>

I am using the PHP error_log and I am getting this error for each variable table, column, value, etc.:

PHP Notice: Trying to get property 'table' of non-object in /update-data.php on line 16.

There is definitely something wrong with the way the info is being posted or with how the posted info is being retrieved, not with the SQL.

Thank you in advance for any help you may be able to provide in sorting out this situation!


Get this bounty!!!

#StackBounty: #php #wp-query #query #search #tax-query How to create a WP_Query to search the Title or Tag?

Bounty: 50

I have created a search using WP_Query, it seems like this query is looking for the queried term in title AND tags.

Is there a way to have this search the title OR tags?

$s = $request['s'];
$tags = str_replace(' ', '-', strtolower($request['s']));

$paged = $request['page'];
$posts_per_page = $request['per_page'];

$result = new WP_Query([
    'post_type'         => 'post',
    'category__in'      => 3060,
    'posts_per_page'    => $posts_per_page,
    'paged'             => $page,
    'orderby'           => 'date',
    'order'             => 'desc',
    's'                 => $s,
    'tag'               => array($tags)
]);


Get this bounty!!!

#StackBounty: #php #wp-admin #mysql #meta-query #sort Sortable admin column for one meta key with three possible meta values

Bounty: 50

I’ve looked over 2 or 3 similar looking threads regarding sortable columns and the meta queries involved with making them work. None seem to resolve my exact problem.

I am using the pre_get_posts filter to hook the sortable logic for an admin column. I have a post meta checkbox that I’d like to sort, it’s key is _prioritize_s.

When checked, the value is 'yes'. If it has never been checked, then neither the key nor value exists. If it’s been checked before, and then unchecked, the key exists, but the value is an empty string.

Here is how I’d like it to order:

  • meta key _prioritize_s = ‘yes’, from the latest to oldest post
  • meta key _prioritize_s = empty string OR NOT EXISTS, from the latest to oldest post

Here is what I have. It kind of works, but the date order doesn’t seem to work properly and I need to group the NOT EXISTS query with the one where the value could be an empty string?

class Featured_Admin_column {

    public $column_names = [
        'prioritized_post' => '_prioritize_s',
    ];

    function init() {
        $this->hooks();
    }

    function hooks() {
        add_filter( 'manage_edit-post_sortable_columns', [ $this, 'create_sortable_columns' ] );
        add_action( 'pre_get_posts', [ $this, 'set_meta_for_sortable_columns' ] );

    }

    function create_sortable_columns( $columns ) {
        $columns['prioritized_post'] = 'priority';

        return $columns;
    }

    function set_meta_for_sortable_columns( $query ) {
        if ( ! is_admin() ) {
            return;
        }

        $orderby = $query->get( 'orderby' );
        if ( 'priority' == $orderby ) {
            $query->set( 'meta_query', array(
                'relation' => 'OR',
                array(
                    'key'   => '_prioritize_s',
                    'value' => 'yes',
                ),
                //The 2 arrays below should be grouped together somehow...
                array(
                    'key'   => '_prioritize_s',
                    'value' => '',
                ),
                array(
                    'key'     => '_prioritize_s',
                    'compare' => 'NOT EXISTS'
                )
            ) );

            $query->set( 'orderby', 'meta_value date' );
        }
    }

Update: I’ve tried messing around with this some more, and thinking maybe WP considers blank values as null as well. When I tried putting the meta query on a page template so I could echo out things and test before I mess with the admin columns, I tried reducing the meta query for 2 arrays instead of 3. I get both posts with and without the post meta _prioritize_s but the date order is still out of whack despite using an array in the orderby. What am I missing?

$test_sorting_by_priority = get_posts( [
    'posts_per_page' => - 1,
    'order'          => 'DESC',
    'orderby' => array(
        'exists' => 'date',
        'empty' => 'date',
    ),
    'meta_query'     => array(
        'relation' => 'OR',
        'exists'   => array(
            'key'     => '_prioritize_s',
            'value'   => 'yes',
            'compare' => 'EXISTS',
        ),
        'empty'    => array(
            'key'     => '_prioritize_s',
            'compare' => 'NOT EXISTS'
        ),
    ),
] );

foreach ( $test_sorting_by_priority as $test ) {
    $empty_or_null = isset( $test->{'_prioritize_s'}) ? $test->{'_prioritize_s'} : 'null';

    echo $test->ID . ' ================== <b>' . $test->post_date . ' ===== ' . $empty_or_null . '</b> <br/>';
}


Get this bounty!!!

#StackBounty: #php #xml #xslt #xml-parsing #simplexml Get xml file to find and replace text. PHP

Bounty: 150

I need to change texts in a XML file using PHP code. Then I created a code to:

1- get the file

2- replace the texts

3- save the file with other name.

Problem is that I am having some issues to replace some text in a xml file.

I am able to replace simples strings but I can not replace text with characters like ‘<‘. Below the real code and files.

Original XML path: http://www.csainmobiliaria.com/imagenes/fotos/pisos-NOK.xml

1) This code just changes the text Inmuebles to xxxxxxxx. This works fine

    $xml_external_path = 'http://www.csainmobiliaria.com/imagenes/fotos/pisos-NOK.xml';
$xml = file_get_contents($xml_external_path);

$response = strtr($xml, array(
    'Inmuebles' => 'xxxxxxxx'
));

$newXml = $response;

$newXml = simplexml_load_string( $newXml );
$newXml->asXml('/home/csainmobiliaria/www/pisos-NEW.xml');

2) Now, if I use this code to change the text <Table Name="Inmuebles"> to <xxxxxxxx> I get a ERROR 500.

    $xml_external_path = 'http://www.csainmobiliaria.com/imagenes/fotos/pisos-NOK.xml';
$xml = file_get_contents($xml_external_path);

$response = strtr($xml, array(
    '<Table Name="Inmuebles">' => '<xxxxxxxx>'
));

$newXml = $response;

$newXml = simplexml_load_string( $newXml );
$newXml->asXml('/home/csainmobiliaria/www/pisos-NEW.xml');

3) In the same way, if I use this code to remove the text Publicacion I get a ERROR 500.

    $xml_external_path = 'http://www.csainmobiliaria.com/imagenes/fotos/pisos-NOK.xml';
$xml = file_get_contents($xml_external_path);

$response = strtr($xml, array(
    '<Publicacion>' => ''
));

$newXml = $response;

$newXml = simplexml_load_string( $newXml );
$newXml->asXml('/home/csainmobiliaria/www/pisos-NEW.xml');

This is the final result I need to get:http://www.csainmobiliaria.com/imagenes/fotos/pisos-OK.xml

Capture: enter image description here


Get this bounty!!!

#StackBounty: #bash #scripts #apache2 #php How to execute script on my Ubuntu via PHP from site

Bounty: 50

How can I use PHP to execute a script on my Ubuntu server? The site is hosted on the same machine obviously.

I read about exec_shell() and tried this

<?php
    $output = shell_exec("ls /var/www");
    echo "<h1>Output: " . $output . "</h1>";
?>

But it didn’t echo anything on the site, have I misunderstood the function?

Plan is to make a script run on my Ubuntu PC, restarting a few game servers once I click a button on the website.


Get this bounty!!!