Migrate legacy has_one featured image to many_many relation

@param HTTPRequest $request
@return
495653
public function run($request)
    {
        // @TODO: the below function needs to be rewritten to loop over all DataObjects which have been extended with FeaturedImage for this task to actually work.
        die("FeaturedImageUpdateTask hasn't actually been fully implemented; run() needs to be rewritten to loop over all DataObjects which have been extended with FeaturedImage for this task to actually work");

        // Perform migrations (the legacy field will be left in the DB by the ORM)
        $class = $this->owner->class;
        $baseclass = $this->ownerBaseClass;
        // check if table exists before attempting update, else this may throw an error on new installs
        if ($baseclass == $class && array_search($baseclass, DB::table_list())) {
            // if(in_array('FeaturedImageExtension', Config::inst()->get($class, 'extensions'))){
            $rows = DB::query('SELECT * FROM "' . $baseclass . '"');
            $altered = false;
            foreach ($rows as $page) {
                if (array_key_exists('FeaturedImageID', $page) && $imageID = $page['FeaturedImageID']) {
                    DB::query('INSERT INTO "' . $baseclass . '_FeaturedImages" (' . $class . 'ID, ImageID) VALUES (' . $page['ID'] . ', ' . $page['FeaturedImageID'] . ')');
                    $altered = true;
                    //$page->FeaturedImages()->add($imageID);
                    //$page->FeaturedImageID = null; // leave as is...
//					$page->write();
                }
            }
            // Now drop the legacy field
            if ($altered) {
                DB::query('ALTER TABLE "' . $baseclass . '" DROP "FeaturedImageID"');
                DB::alteration_message('Migrated FeaturedImages to many_many on ' . $baseclass, 'changed');
            }
        }
    }
75511
public function deleteCampaign(HTTPRequest $request)
    {
        // Check security ID
        if (!SecurityToken::inst()->checkRequest($request)) {
            return new HTTPResponse(null, 400);
        }

        $id = $request->param('ID');
        if (!$id || !is_numeric($id)) {
            return (new HTTPResponse(null, 400));
        }

        $record = ChangeSet::get()->byID($id);
        if (!$record) {
            return (new HTTPResponse(null, 404));
        }

        if (!$record->canDelete()) {
            return (new HTTPResponse(null, 403));
        }

        $record->delete();

        return (new HTTPResponse(null, 204));
    }
716575
public function insertCrud(Request $request)
    {
        $validation = Validator::make($request->all(), [
            'name'  => 'required|unique:menus,name',
            'title' => 'required',
            'soft'  => 'required',
        ]);
        if ($validation->fails()) {
            return redirect()->back()->withInput()->withErrors($validation);
        }
        // Get model names
        $menus  = Menu::all();
        $models = [];
        foreach ($menus as $menu) {
            $tableName         = strtolower($menu->name);
            $models[$menu->id] = $tableName;
        }
        // Init QuickCache
        $cache                   = new QuickCache();
        $cached                  = [];
        $cached['relationships'] = 0;
        $cached['files']         = 0;
        $cached['password']      = 0;
        $cached['date']          = 0;
        $cached['datetime']      = 0;
        $cached['enum']          = 0;
        $fields                  = [];

        foreach ($request->f_type as $index => $field) {
            $fields[$index] = [
                'type'               => $field,
                'title'              => $request->f_title[$index],
                'label'              => $request->f_label[$index],
                'helper'             => $request->f_helper[$index],
                'validation'         => $request->f_validation[$index],
                'value'              => $request->f_value[$index],
                'default'            => $request->f_default[$index],
                'relationship_id'    => $request->has('f_relationship.' . $index) ? $request->f_relationship[$index] : '',
                'relationship_name'  => $request->has('f_relationship.' . $index) ? isset($models[$request->f_relationship[$index]]) ? $models[$request->f_relationship[$index]] : '' : '',
                'relationship_field' => $request->has('f_relationship_field.' . $request->f_relationship[$index]) ? $request->f_relationship_field[$request->f_relationship[$index]] : '',
                'texteditor'         => $request->f_texteditor[$index],
                'size'               => $request->f_size[$index] * 1024,
                'show'               => $request->f_show[$index],
                'dimension_h'        => $request->f_dimension_h[$index],
                'dimension_w'        => $request->f_dimension_w[$index],
                'enum'               => $request->f_enum[$index],
            ];
            if ($field == 'relationship') {
                $cached['relationships']++;
            } elseif ($field == 'file' || $field == 'photo') {
                $cached['files']++;
            } elseif ($field == 'password') {
                $cached['password']++;
            } elseif ($field == 'date') {
                $cached['date']++;
            } elseif ($field == 'datetime') {
                $cached['datetime']++;
            } elseif ($field == 'enum') {
                $cached['enum']++;
            }
        }
//        dd($fields);
        $cached['fields']      = $fields;
        $cached['name']        = $request->name;
        $cached['soft_delete'] = $request->soft;
        $cache->put('fieldsinfo', $cached);
        // Create menu entry
        $menu = Menu::create([
            'position'  => 0,
            'icon'      => $request->icon != '' ? $request->icon : 'fa-database',
            'name'      => $request->name,
            'title'     => $request->title,
            'parent_id' => $request->parent_id ?: null,
        ]);
        $menu->roles()->sync($request->input('roles', []));
        // Create migrations
        $migrationBuilder = new MigrationBuilder();
        $migrationBuilder->build();
        // Create model
        $modelBuilder = new ModelBuilder();
        $modelBuilder->build();
        // Create request
        $requestBuilder = new RequestBuilder();
        $requestBuilder->build();
        // Create controller
        $controllerBuilder = new ControllerBuilder();
        $controllerBuilder->build();
        // Create views
        $viewsBuilder = new ViewsBuilder();
        $viewsBuilder->build();

        // Call migrations
        Artisan::call('migrate');

        // Destroy our cache file
        $cache->destroy('fieldsinfo');

        return redirect(config('quickadmin.route'));
    }
464339
public function duplicateAction(Request $request)
    {
        /* @var $rep ItemRepository */
        $rep = $this->getDoctrine()->getRepository('AnimeDbCatalogBundle:Item');

        // get store item
        $item = $request->getSession()->get(self::NAME_ITEM_ADDED);
        if (!($item instanceof Item)) {
            throw $this->createNotFoundException('Not found item for confirm duplicate');
        }

        // confirm duplicate
        if ($request->isMethod('POST')) {
            $request->getSession()->remove(self::NAME_ITEM_ADDED);
            switch ($request->request->get('do')) {
                case 'add':
                    return $this->addItem($item->freez($this->getDoctrine()));
                default:
                    return $this->redirect($this->generateUrl('home'));
            }
        }

        // re searching for duplicates
        $duplicate = $rep->findDuplicate($item);
        // now there is no duplication
        if (!$duplicate) {
            return $this->addItem($item->freez($this->getDoctrine()));
        }

        return $this->render('AnimeDbCatalogBundle:Item:duplicate.html.twig', [
            'items' => $duplicate,
        ]);
    }
1266543
public function imagesAction(Request $request)
    {
        $locator = $this->get('pattern_locator');
        $files = $locator->locate('*.gif', 'public/elementtypes', false);
        $prefix = $request->getBasePath().'/bundles/phlexibleelementtype/elementtypes/';

        foreach ($files as $file) {
            $data[basename($file)] = [
                'title' => basename($file),
                'url' => $prefix.basename($file),
            ];
        }

        ksort($data);
        $data = array_values($data);

        return new JsonResponse(['images' => $data]);
    }
598188
public function getAll($uuid, Request $request)
    {
        $parentModel = static::$parentModel;
        $parentResource = $parentModel::findOrFail($uuid);

        // Authorize ability to view children models for parent
        $this->authorizeUserAction($this->parentAbilitiesRequired['view'], $parentResource);

        $model = static::$model;
        $resourceRelationName = model_relation_name($model);

        // Form model's with relations for parent query
        $withArray = [];
        foreach ($model::$localWith as $modelRelation) {
            $withArray[] = $resourceRelationName . '.' . $modelRelation;
        }

        $withArray = array_merge([$resourceRelationName], $withArray);

        $parentResource = $parentResource->where($parentResource->getKeyName(), '=', $parentResource->getKey())->with($withArray)->first();

        $collection = $parentResource->getRelationValue($resourceRelationName);

        if ($collection == null) {
            $collection = new Collection();
        }

        return $this->response->collection($collection, $this->getTransformer());
    }
91422
public function multipledeleteinfoAction(Request $request)
    {
        $ids = $request->get('ids');

        $response = [];
        $numContacts = 0;
        $numChildren = 0;

        foreach ($ids as $id) {
            $account = $this->getRepository()->countDistinctAccountChildrenAndContacts($id);

            // Get number of subaccounts.
            $numChildren += $account['numChildren'];

            // FIXME: Distinct contacts: (currently the same contacts could be counted multiple times).
            // Get full number of contacts.
            $numContacts += $account['numContacts'];
        }

        $response['numContacts'] = $numContacts;
        $response['numChildren'] = $numChildren;

        $view = $this->view($response, 200);

        return $this->handleView($view);
    }
320408
public function upload(SS_HTTPRequest $request)
    {
        if (!$this->currentVersionFile) {
            return;
        }


        if ($this->isDisabled() || $this->isReadonly()) {
            return $this->httpError(403);
        }

        // Protect against CSRF on destructive action
        $token = $this->getForm()->getSecurityToken();
        if (!$token->checkRequest($request)) {
            return $this->httpError(400);
        }

        $name = $this->getName();
        $tmpfile = $request->postVar($name);
        $record = $this->getRecord();
        
        // Check if the file has been uploaded into the temporary storage.
        if (!$tmpfile) {
            $return = array('error' => _t('UploadField.FIELDNOTSET', 'File information not found'));
        } else {
            $return = array(
                'name' => $tmpfile['name'],
                'size' => $tmpfile['size'],
                'type' => $tmpfile['type'],
                'error' => $tmpfile['error']
            );
        }

        // Check for constraints on the record to which the file will be attached.
        if (!$return['error'] && $this->relationAutoSetting && $record && $record->exists()) {
            $tooManyFiles = false;
            // Some relationships allow many files to be attached.
            if ($this->getConfig('allowedMaxFileNumber') && ($record->has_many($name) || $record->many_many($name))) {
                if (!$record->isInDB()) {
                    $record->write();
                }
                $tooManyFiles = $record->{$name}()->count() >= $this->getConfig('allowedMaxFileNumber');
            // has_one only allows one file at any given time.
            } elseif ($record->has_one($name)) {
                $tooManyFiles = $record->{$name}() && $record->{$name}()->exists();
            }

            // Report the constraint violation.
            if ($tooManyFiles) {
                if (!$this->getConfig('allowedMaxFileNumber')) {
                    $this->setConfig('allowedMaxFileNumber', 1);
                }
                $return['error'] = _t(
                    'UploadField.MAXNUMBEROFFILES',
                    'Max number of {count} file(s) exceeded.',
                    array('count' => $this->getConfig('allowedMaxFileNumber'))
                );
            }
        }

        // Process the uploaded file
        if (!$return['error']) {
            // Get the uploaded file into a new file object.
            try {
                $currentFilePath = $this->currentVersionFile->getFullPath();
                if (file_exists($currentFilePath)) {
                    unlink($this->currentVersionFile->getFullPath());
                }

                // If $folderName == assets (by default), then this will try and create a file inside assets/assets
                // instead of creating it in the root. This check ensures that the newly uploaded files overwrites the
                // old file in the assets root directory.
                $folderName = $this->folderName;
                if ($folderName == basename(ASSETS_PATH)) {
                    $folderName = "/";
                }

                $this->upload->loadIntoFile(
                    array_merge($tmpfile, array('name' => $this->currentVersionFile->Name)),
                    $this->currentVersionFile,
                    $folderName
                );
            } catch (Exception $e) {
                // we shouldn't get an error here, but just in case
                $return['error'] = $e->getMessage();
            }

            if (!$return['error']) {
                if ($this->upload->isError()) {
                    $return['error'] = implode(' '.PHP_EOL, $this->upload->getErrors());
                } else {
                    $file = $this->upload->getFile();

                    $file->createVersion();

                    // Attach the file to the related record.
                    if ($this->relationAutoSetting) {
                        $this->attachFile($file);
                    }

                    // Collect all output data.
                    $file =  $this->customiseFile($file);
                    $return = array_merge($return, array(
                        'id' => $file->ID,
                        'name' => $file->getTitle() . '.' . $file->getExtension(),
                        'url' => $file->getURL(),
                        'thumbnail_url' => $file->UploadFieldThumbnailURL,
                        'edit_url' => $file->UploadFieldEditLink,
                        'size' => $file->getAbsoluteSize(),
                        'buttons' => $file->UploadFieldFileButtons
                    ));
                }
            }
        }
        $response = new SS_HTTPResponse(Convert::raw2json(array($return)));
        $response->addHeader('Content-Type', 'text/plain');
        return $response;
    }
1075037
public function cgetAction(Request $request)
    {
        $locale = $this->getRequestParameter($request, 'locale', true);
        $list = new CollectionRepresentation(
            $this->getManager()->findAllByLocale($locale),
            self::$entityKey
        );

        $view = $this->view($list, 200);

        return $this->handleView($view);
    }
256136
public function getOneFromParent($uuid, Request $request)
    {
        $parentModel = static::$parentModel;
        $parentResource = $parentModel::findOrFail($uuid);

        // Authorize ability to view children models for parent
        $this->authorizeUserAction($this->parentAbilitiesRequired['view'], $parentResource);

        $model = static::$model;
        $resourceRelationName = model_relation_name($model, 'one');

        // Form model's with relations for parent query
        $withArray = [];
        foreach ($model::$localWith as $modelRelation) {
            $withArray[] = $resourceRelationName . '.' . $modelRelation;
        }

        $withArray = array_merge([$resourceRelationName], $withArray);
        $parentResource = $parentResource->where($parentResource->getKeyName(), '=', $parentResource->getKey())->with($withArray)->first();

        $resource = $parentResource->getRelationValue($resourceRelationName);

        // Make sure it exists, and if so, authorize view action
        if ($resource == null) {
            throw new NotFoundHttpException('Can not find a "' . $resourceRelationName . '" attached to this ' . (new \ReflectionClass($parentModel))->getShortName());
        } else {
            // Authorize ability to view this model
            $this->authorizeUserAction('view', $resource);
        }

        return $this->response->item($resource, $this->getTransformer());
    }
1185659
public function afterSave(\Illuminate\Http\Request $request)
    {
        if (is_null($this->getModelForOptions())) {
            return;
        }

        if ($this->isValueSkipped()) {
            return;
        }

        $attribute = $this->getModelAttributeKey();

        if (is_null($request->input($this->getPath()))) {
            $values = [];
        } else {
            $values = $this->getValueFromModel();
        }

        $relation = $this->getModel()->{$attribute}();

        if ($relation instanceof \Illuminate\Database\Eloquent\Relations\BelongsToMany) {
            $this->syncBelongsToManyRelation($relation, $values);
        } elseif ($relation instanceof \Illuminate\Database\Eloquent\Relations\HasMany) {
            $this->deleteOldItemsFromHasManyRelation($relation, $values);
            $this->attachItemsToHasManyRelation($relation, $values);
        }
    }
799375
public function handle($request)
    {
        $entity = $this->repository()->findById($request->getId());
        $this->authorize($request, $entity);

        foreach ($request->getData() as $raw) {
            $item = $this->getRelatedEntity($raw);
            $this->addRelationItem($entity, $this->field(), $item);
        }

        $this->repository()->getEntityManager()->flush($entity);

        return (
            new RelatedCollectionAction(
                $this->repository(),
                $this->mappedBy(),
                $this->related(),
                $this->transformer()
            )
        )->dispatch($request)->setStatusCode(RestResponse::HTTP_CREATED);
    }
355535
public function migrate($request) {
		$migrationTarget 		= isset($request['MigrationTarget']) ? $request['MigrationTarget'] : '';
		$fileMigrationTarget 	= isset($request['FileMigrationTarget']) ? $request['FileMigrationTarget'] : '';
		$includeSelected 		= isset($request['IncludeSelected']) ? $request['IncludeSelected'] : 0;
		$includeChildren 		= isset($request['IncludeChildren']) ? $request['IncludeChildren'] : 0;
		$duplicates 			= isset($request['DuplicateMethod']) ? $request['DuplicateMethod'] : ExternalContentTransformer::DS_OVERWRITE;
		$selected 				= isset($request['ID']) ? $request['ID'] : 0;

		if(!$selected){
			$messageType = 'bad';
			$message = _t('ExternalContent.NOITEMSELECTED', 'No item selected to import.');
		}

		if(!$migrationTarget || !$fileMigrationTarget){
			$messageType = 'bad';
			$message = _t('ExternalContent.NOTARGETSELECTED', 'No target to import to selected.');
		}

		if ($selected && ($migrationTarget || $fileMigrationTarget)) {
			// get objects and start stuff
			$target = null;
			$targetType = 'SiteTree';
			if ($migrationTarget) {
				$target = DataObject::get_by_id('SiteTree', $migrationTarget);
			} else {
				$targetType = 'File';
				$target = DataObject::get_by_id('File', $fileMigrationTarget);
			}

			$from = ExternalContent::getDataObjectFor($selected);
			if ($from instanceof ExternalContentSource) {
				$selected = false;
			}

			if (isset($request['Repeat']) && $request['Repeat'] > 0) {
				$job = new ScheduledExternalImportJob($request['Repeat'], $from, $target, $includeSelected, $includeChildren, $targetType, $duplicates, $request);
				singleton('QueuedJobService')->queueJob($job);

				$messageType = 'good';
				$message = _t('ExternalContent.CONTENTMIGRATEQUEUED', 'Import job queued.');
			} else {
				$importer = $from->getContentImporter($targetType);
				if ($importer) {
					$result = $importer->import($from, $target, $includeSelected, $includeChildren, $duplicates, $request);

					$messageType = 'good';
					if ($result instanceof QueuedExternalContentImporter) {
						$message = _t('ExternalContent.CONTENTMIGRATEQUEUED', 'Import job queued.');
					} else {
						$message = _t('ExternalContent.CONTENTMIGRATED', 'Import Successful.');
					}
				}
			}
		}

		Session::set("FormInfo.Form_EditForm.formError.message",$message);
		Session::set("FormInfo.Form_EditForm.formError.type", $messageType);

		return $this->getResponseNegotiator()->respond($this->request);
	}
70050
public function index(HTTPRequest $request = null)
    {
        $gallery = $this->Gallery();
        if ($this->Content && $gallery) {
            $hasLocation = stristr($this->Content, '$Gallery');
            if ($hasLocation) {
                /** @see Requirements_Backend::escapeReplacement */
                $galleryEscapedForRegex = addcslashes($gallery->forTemplate(), '\\$');
                $content = preg_replace(
                    '/(<p[^>]*>)?\\$Gallery(<\\/p>)?/i',
                    $galleryEscapedForRegex,
                    $this->Content
                );
                return [
                    'Content' => DBField::create_field('HTMLText', $content),
                    'Gallery' => ''
                ];
            }
        }

        return [
            'Content' => DBField::create_field('HTMLText', $this->Content),
            'Gallery' => $this->Gallery()
        ];
    }
459752
public function sortAction(Request $request)
    {
        $ids = $request->request->get('ids');

        if (!is_array($ids)) {
            throw $this->createNotFoundException(sprintf('Query parameter "ids" must be an array, got "%s".', gettype($ids)));
        }
        if (empty($ids)) {
            return new Response();
        }

        /** @var \Darvin\ImageBundle\Entity\Image\AbstractImage[] $images */
        $images = $positions = [];

        foreach ($this->getImages($ids) as $image) {
            $images[$image->getId()] = $image;
            $positions[] = $image->getPosition();
        }
        foreach ($ids as $index => $id) {
            $images[$id]->setPosition($positions[$index]);
        }

        $this->getDoctrine()->getManager()->flush();

        return new Response();
    }
833222
public function newAction(Request $request)
    {
        $menu = new MenuItem();
        $form = $this->createForm('CoreExtraBundle\Form\MenuItemType', $menu, array('uploadDir'=> 'uploads/images/menu'));
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            
            //clean image form
            $this->get('core_manager')->cleanImageForm($request->files->get('menu_item'), $menu);
            
            $em = $this->getDoctrine()->getManager();
            $em->persist($menu);
            $em->flush();
            
            //images
            $image = $form->getNormData()->getImage();
            if ($image instanceof Image) {
                $this->get('core_manager')->uploadMenuImage($menu);
            }
            
            $this->get('session')->getFlashBag()->add('success', 'menu.created');

            return $this->redirectToRoute('coreextra_menuitem_show', array('id' => $menu->getId()));
        }

        return array(
            'entity' => $menu,
            'form' => $form->createView(),
        );
    }
7086
public function tree(HTTPRequest $request)
    {
        // Regular source specification
        $isSubTree = false;

        $this->search = $request->requestVar('search');
        $id = (is_numeric($request->latestParam('ID')))
            ? (int)$request->latestParam('ID')
            : (int)$request->requestVar('ID');

        // pre-process the tree - search needs to operate globally, not locally as marking filter does
        if ($this->search) {
            $this->populateIDs();
        }

        /** @var DataObject|Hierarchy $obj */
        $obj = null;
        $sourceObject = $this->getSourceObject();

        // Precache numChildren count if possible.
        if ($this->getNumChildrenMethod() == 'numChildren') {
            // We're not calling `Hierarchy::prepopulateTreeDataCache()` because we're not customising results based
            // on version or Fluent locales. So there would be no performance gain from additional caching.
            Hierarchy::prepopulate_numchildren_cache($sourceObject);
        }

        if ($id && !$request->requestVar('forceFullTree')) {
            $obj = DataObject::get_by_id($sourceObject, $id);
            $isSubTree = true;
            if (!$obj) {
                throw new Exception(
                    "TreeDropdownField->tree(): the object #$id of type $sourceObject could not be found"
                );
            }
        } else {
            if ($this->getTreeBaseID()) {
                $obj = DataObject::get_by_id($sourceObject, $this->getTreeBaseID());
            }

            if (!$this->getTreeBaseID() || !$obj) {
                $obj = DataObject::singleton($sourceObject);
            }
        }

        // Create marking set
        $markingSet = MarkedSet::create(
            $obj,
            $this->getChildrenMethod(),
            $this->getNumChildrenMethod(),
            $this->config()->get('node_threshold_total')
        );

        // Set filter on searched nodes
        if ($this->getFilterFunction() || $this->search) {
            // Rely on filtering to limit tree
            $markingSet->setMarkingFilterFunction(function ($node) {
                return $this->filterMarking($node);
            });
            $markingSet->setLimitingEnabled(false);
        }

        // Begin marking
        $markingSet->markPartialTree();

        // Explicitely mark our search results if necessary
        foreach ($this->searchIds as $id => $marked) {
            if ($marked) {
                $object = $this->objectForKey($id);
                if (!$object) {
                    continue;
                }
                $markingSet->markToExpose($object);
            }
        }

        // Allow to pass values to be selected within the ajax request
        $value = $request->requestVar('forceValue') ?: $this->value;
        if ($value && ($values = preg_split('/,\s*/', $value))) {
            foreach ($values as $value) {
                if (!$value || $value == 'unchanged') {
                    continue;
                }

                $object = $this->objectForKey($value);
                if (!$object) {
                    continue;
                }
                $markingSet->markToExpose($object);
            }
        }

        // Set title formatter
        $customised = function (DataObject $child) use ($isSubTree) {
            return [
                'name' => $this->getName(),
                'id' => $child->obj($this->getKeyField()),
                'title' => $child->obj($this->getTitleField()),
                'treetitle' => $child->obj($this->getLabelField()),
                'disabled' => $this->nodeIsDisabled($child),
                'isSubTree' => $isSubTree
            ];
        };

        // Determine output format
        if ($request->requestVar('format') === 'json') {
            // Format JSON output
            $json = $markingSet
                ->getChildrenAsArray($customised);

            if ($request->requestVar('flatList')) {
                // format and filter $json here
                $json['children'] = $this->flattenChildrenArray($json['children']);
            }
            return HTTPResponse::create()
                ->addHeader('Content-Type', 'application/json')
                ->setBody(json_encode($json));
        } else {
            // Return basic html
            $html = $markingSet->renderChildren(
                [self::class . '_HTML', 'type' => 'Includes'],
                $customised
            );
            return HTTPResponse::create()
                ->addHeader('Content-Type', 'text/html')
                ->setBody($html);
        }
    }