Fetch/Remove all unused assets (by plugin) The title is self-explanatory, but I need to buid a service function to remove unused assets, or at least to fetch those in order to delete found assets after.

Any simple solution?
This should work

//First fetch all ids from elements table
$allIds = craft()-&gt;db-&gt;createCommand()-&gt;select('id')-&gt;from('elements')-&gt;where([
    'not like', 'type', 'Asset'
])-&gt;queryColumn();

// query for all related Assets -&gt; assets that are used somewhere
$usedAssetCriteria = craft()-&gt;elements-&gt;getCriteria(ElementType::Asset);
$usedAssetCriteria-&gt;relatedTo = $allIds;
$usedAssetCriteria-&gt;limit = null;
$usedAssets = $usedAssetCriteria-&gt;ids();

// query for all assets not in the list of the used one
$unUsedCriteria = craft()-&gt;elements-&gt;getCriteria(ElementType::Asset);
$unUsedCriteria-&gt;id = 'and, not ' . implode(', not ', $usedAssets);
craft()-&gt;assets-&gt;deleteFiles($unUsedCriteria-&gt;ids());