РЕШЕНО - Загрузка картинок из фроненда

Доброго времени суток. Нагуглил такие вот сниппеты для создания ресурсов из фронтенда:

1 — Отвечает за заполнение указаных в ФормИТ полей:

<?php
$doc = $modx->getObject('modResource',array('id'=>$hook->getValue('resource_id')));
if (empty($doc)){
    $doc = $modx->newObject('modResource');
    $doc->set('createdby', $modx->user->get('id'));
}
else{
    $doc->set('editedby', $modx->user->get('id'));
}
$allFormFields = $hook->getValues();
foreach ($allFormFields as $field=>$value)
{
   if ($field !== 'spam' && $field !== 'resource_id'){
         $doc->set($field, $value);
    }
}
$alias = $doc->cleanAlias($fields['pagetitle']);
if($modx->getCount(modResource, array('alias'=>$alias))!= 0) {
$count = 1;
$newAlias = $alias;
while($modx->getCount(modResource, array('alias'=>$newAlias))!= 0) {
$newAlias = $alias;
$newAlias .= '-' . $count;
$count++;
}
$alias = $newAlias;
}
$doc->set('alias',$alias);
$doc->set('template', $template);
$doc->save();
foreach ($allFormFields as $field=>$value)
{
    if (!empty($value) && $tv = $modx->getObject('modTemplateVar', array ('name'=>$field)))
    {
        /* handles checkboxes & multiple selects elements */
        if (is_array($value)) {
            $featureInsert = array();
            while (list($featureValue, $featureItem) = each($value)) {
                $featureInsert[count($featureInsert)] = $featureItem;
            }
            $value = implode('||',$featureInsert);
        }
        $tv->setValue($doc->get('id'), $value);
        $tv->save();
    }
}
$modx->cacheManager->refresh();
return true;


2 — загружает файлы на сервер и забивает путь к ним в нужные ТВ:

<?php
// initialize output;
$output = true;
$counter = 1;
// valid extensions
$ext_array = array('jpg', 'png', 'gif', 'jpeg', 'JPG', 'PNG', 'GIF', 'JPEG');
$mydir = $modx->user->get('id'); // Path from root that user specifies
// create unique path for this form submission
$uploadpath = 'assets/uploads/'.$mydir.'/';
// get full path to unique folder
$target_path = $modx->config['base_path'] . $uploadpath;
// get uploaded file names:
$submittedfiles = array_keys($_FILES);
// loop through files
foreach ($submittedfiles as $sf) {
    // Get Filename and make sure its good.
    $filename = basename( $_FILES[$sf]['name'] );
    // Get file's extension
    $ext = pathinfo($filename, PATHINFO_EXTENSION);
    $ext = mb_strtolower($ext); // case insensitive
    // is the file name empty (no file uploaded)
    if($filename != '') {
        // is this the right type of file?
        if(in_array($ext, $ext_array)) {
            // clean up file name and make unique
            $filename = $counter . '.' . $ext;
            $filename = str_replace(' ', '_', $filename); // spaces to underscores
            $filename = date("Y-m-d_G-i-s_") . $filename; // add date & time
            // full path to new file
            $myTarget = $target_path . $filename;
            // create directory to move file into if it doesn't exist
            mkdir($target_path, 0755, true);
            // is the file moved to the proper folder successfully?
            if(move_uploaded_file($_FILES[$sf]['tmp_name'], $myTarget)) {
                // set a new placeholder with the new full path (if you need it in subsequent hooks)
                $myFile = $uploadpath . $filename;
                $hook->setValue($sf,$myFile);
                // set the permissions on the file
                if (!chmod($myTarget, 0644)) { /*some debug function*/ }
            } else {
                // File not uploaded
                $errorMsg = 'There was a problem uploading the file.';
                $hook->addError($sf, $errorMsg);
                $output = false; // generate submission error
            }
        } else {
            // File type not allowed
            $errorMsg = 'Type of file not allowed.';
            $hook->addError($sf, $errorMsg);
            $output = false; // generate submission error
        }
    // if no file, don't error, but return blank
    } else {
        $hook->setValue($sf, '');
    }
$counter = $counter + 1;
}
return $output;


2й мне нужен только для загрузки картинок, но он вставляет в ТВ строчку, подобную этой:

london_lights_by_bluerain0789-d5hn65m.jpg||image/jpeg||D:\OpenServer\userdata\temp\php873C.tmp||0||5460308
Что приводит к полному провалу все затеи. Я пытался копать в сторону проблем загрузки файлов наОпенСервере, но ничего не нагуглил, к сожалению. В другие ТВ, например, цена, вставляется все нормально.
MrKarandash
07 октября 2013, 21:22
modx.pro
1
2 097
0

Комментарии: 5

MrKarandash
08 октября 2013, 01:32
0
Забыл добавить, папка создается, файл загружается на сервер исправно, но путь до него приходит вида как я обозначил выше
    Василий Наумкин
    08 октября 2013, 01:36
    0
    Я использую Tickets + Uploadify — никаких проблем.

    И страницы создаются, и картинки загружаются.
      MrKarandash
      08 октября 2013, 01:52
      0
      я не уверен, что это ошибка сниппета. В любом случае хочется разобраться в проблеме, какой бы она не была, а не эксперементировать с 500 рублями. Возможно проблема в настройке ОпенСервера всего лишь
      MrKarandash
      08 октября 2013, 02:25
      0
      При вызове FormIT хук (сниппет) с обработкой файлов вызывать первым, после него хук (сниппет) обработки полей и затем все остальное
        Александр Котлов
        08 октября 2013, 03:06
        0
        Любое из дополнений Василия — как раз тот случай когда можно смело эксперементировать с рублями)
        Авторизуйтесь или зарегистрируйтесь, чтобы оставлять комментарии.
        5