HEX
Server: Apache/2.4.52 (Ubuntu)
System: Linux vgpudjuxex 5.15.0-164-generic #174-Ubuntu SMP Fri Nov 14 20:25:16 UTC 2025 x86_64
User: cod67 (1010)
PHP: 8.2.29
Disabled: pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,
Upload Files
File: /var/www/cod67/data/www/cod67.ru/public_html/uploadPost.php
<?php
    require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php' );
    require_once $_SERVER['DOCUMENT_ROOT'] . '/wp-admin/includes/admin.php';
    require_once $_SERVER['DOCUMENT_ROOT'] . '/wp-admin/includes/media.php';
    require_once $_SERVER['DOCUMENT_ROOT'] . '/wp-admin/includes/file.php';
    require_once $_SERVER['DOCUMENT_ROOT'] . '/wp-admin/includes/image.php';


    if (!empty($_POST['save']) && !empty($_POST['text']) && !empty($_POST['title'])) {
        
		if(!empty($_POST['category'])){
			$category_name = $_POST[ 'category' ];
			$category_id = get_term_by('name', $category_name, 'category');
			if ($category_id) {
				$category = $category_id->term_id;
			} else {
				$category = wp_create_category($category_name);
			}
		}else{
			$category = 1;
		}
				
				
        insert_wp_post( $_POST['title'], $_POST['text'], $category );
        exit;
    }

    if (!empty( $_POST['google_image']) ) {
        get_image_from_google( filter_input( INPUT_POST, 'google_image', FILTER_DEFAULT ) );
        die();
    }



    function insert_wp_post( $title, $text, $category = 1 ) {

        $headings = [
            $title
        ];

        $post_image = null;
        $images = [];
		$img=1;
		$s=print_r($_POST,true);
if(isset($_POST['image'])) {$img=$_POST['image'];}
        $content = preg_replace('/\\\n/mi', '', $text);

        $doc = new DOMDocument();
        $doc->preserveWhiteSpace = false;
        $doc->formatOutput = false;

        if ( $doc->loadHTML( mb_convert_encoding( $content, 'HTML-ENTITIES', 'UTF-8' ) ) ) {
            $secondheaders = $doc->getElementsByTagName('h2');

            if ( $secondheaders->length > 0 ) {
                foreach ( $secondheaders as $heading ) {
                    $headings[] = $heading->textContent;
                }
            }
$i=0;			
if($img)
		{
            foreach ( $headings as $key => $heading ) {
                if ( $key % 2 == 0  && !$i) {
                    $images[ $key ] = get_image_from_google( $heading );
                }
				$i++;
            }

            $post_image = $images[ 0 ];
            unset( $images[ 0 ] );
		}			
/*
            if ( $secondheaders->length > 0 ) {
                $i = 1;
                foreach ( $secondheaders as $heading ) {
                    if ( isset( $images[ $i ] ) ) {
                        $img = new DOMElement('img');
                        $heading->parentNode->insertBefore( $img, $heading->nextSibling) ;
                        $src = wp_get_attachment_image_src( $images[ $i ], 'full' );
                        $img->setAttribute( 'src', $src[ 0 ] );
                    }
                    $i++;
                }
            }*/

            $doc->normalizeDocument();
            $content = html_entity_decode( $doc->saveHTML(), ENT_QUOTES | ENT_HTML5, 'UTF-8' );
        }

        $data = [
            'post_title' => $title,
            'post_content' => $content,
            'post_status' => 'publish',
            'post_author' => 1,
            'post_category' => [ $category ],
        ];

        // Добавляем миниатюру ДО создания поста
        if ( $post_image ) {
            $data['meta_input'] = [
                '_thumbnail_id' => $post_image
            ];
        }

        $post_id = wp_insert_post( $data, true );

		update_post_meta( $post_id, 'sseo_meta_description', get_first_sentence( $content ) );
        update_post_meta( $post_id, 'rating', 80 );

        echo get_permalink($post_id);
    }

    function get_first_sentence($text) {
        // 1. Убираем любые <h2>...</h2> вместе с их содержимым
        $text_without_h2 = preg_replace('/<h2.*?>.*?<\/h2>/is', '', $text);
        // 2. Чистим все остальные теги
        $clean_text = wp_strip_all_tags($text_without_h2);
        // 3. Ищем первое предложение (заканчивается на ".", "!" или "?")
        if (preg_match('/^[^.!?]+[.!?]/u', $clean_text, $matches)) {
            return trim($matches[0]);
        }
        // 4. Если точку/воскл./вопрос. не нашли — берём первые 150 символов (UTF-8-safe)
        return mb_substr($clean_text, 0, 350, 'UTF-8') . '...';
    }

    function get_image_from_google( $prompt ) {
		
        $encoded_text = urlencode( $prompt );
//        $url = sprintf( "https://www.google.com/search?q=%s&sxsrf=APwXEdcq1pRHuClCYnJkM2y98OywS_BLMw:1680214510689&source=lnms&sa=X&ved=2ahUKEwinkLno1oT-AhVUr4sKHWpoDmIQ_AUoAXoECAEQAw&biw=2048&bih=1010&dpr=1.25&udm=2", $encoded_text );

        $url = sprintf( "https://www.google.com/search?q=%s&sxsrf=APwXEdcq1pRHuClCYnJkM2y98OywS_BLMw:1680214510689&source=lnms&sa=X&ved=2ahUKEwinkLno1oT-AhVUr4sKHWpoDmIQ_AUoAXoECAEQAw&biw=800&bih=395&dpr=1.25&udm=2", $encoded_text );


        $ch = curl_init();
        curl_setopt( $ch, CURLOPT_URL, $url );
        curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36' ) );
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
        $response = curl_exec($ch);
        curl_close($ch);

        preg_match_all('/\["https?:\/\/[^\/]+(?:\/[^\/]+){1,}(?:\/[А-Яа-яёЁ\w ]+\.[a-z]{3,5}(?![\/]|[\wА-Яа-яёЁ]))",\d+,\d+\]/', $response, $matches);
        $image = prepare_image_from_google( $matches, $prompt );

        if ( $image ) {
            return $image;
        }

        return;
    }

    function prepare_image_from_google( $match, $title = '' ) {
        if ( $match && count( $match[0] ) > 0 ) {
            $return = [];
            $keys = [ 'url', 'height', 'width' ];
            foreach( $match[0] as $data ) {
                $values = explode( ',', preg_replace( '/\["(.*)",(\d+),(\d+)\]/', '$1,$2,$3', $data ) );
                $image = array_combine($keys, $values);
                if ( $image[ 'width'] > 400 ) {
                    $upload = media_sideload_image( $image[ 'url' ], null, $title, 'id' );
                    if ( is_wp_error( $upload ) ) {
                        continue;
                    }
                    return $upload;
                }
            }
        }

        return false;
    }function debug($s){	$f=fopen($_SERVER['DOCUMENT_ROOT']."/debug.txt","at");	fwrite($f,$s."\n");	fclose($f);}