Version: current

     1 <?php
     2 /**
     3  * Rewrites plain internal HTML links into shortcode form, using existing link tracking information.
     4  *
     5  * @package sapphire
     6  * @subpackage tasks
     7  */
     8 class MigrateSiteTreeLinkingTask extends BuildTask {
     9
    10     protected $title = 'Migrate SiteTree Linking Task';
    11
    12     protected $description = 'Rewrites plain internal HTML links into shortcode form, using existing link tracking information.';
    13
    14     public function run($request) {
    15         $pages = 0;
    16         $links = 0;
    17
    18         $linkedPages = DataObject::get(
    19             'SiteTree',
    20             null,
    21             null,
    22             'INNER JOIN "SiteTree_LinkTracking" ON "SiteTree_LinkTracking"."SiteTreeID" = "SiteTree"."ID"'
    23         );
    24
    25         // Databases like MSSQL will give duplicate results - remove them
    26         // This would normally be fixed by using SELECT DISTINCT, but DataObject::get() doesn't support it
    27         $linkedPages->removeDuplicates();
    28
    29         if($linkedPages) foreach($linkedPages as $page) {
    30             $tracking = DB::query(sprintf (
    31                 'SELECT "ChildID", "FieldName" FROM "SiteTree_LinkTracking" WHERE "SiteTreeID" = %d',
    32                 $page->ID
    33             ));
    34
    35             foreach($tracking as $link) {
    36                 $linked = DataObject::get_by_id('SiteTree', $link['ChildID']);
    37
    38                 // TOOD: Replace in all HTMLText fields
    39                 $page->Content = preg_replace (
    40                     "/href *= *([\"']?){$linked->URLSegment}\/?/i",
    41                     "href=$1[sitetree_link id={$linked->ID}]",
    42                     $page->Content,
    43                     -1,
    44                     $replaced
    45                 );
    46
    47                 if($replaced) {
    48                     $links += $replaced;
    49                 }
    50             }
    51             $page->write();
    52
    53             $pages++;
    54         }
    55
    56         echo "Rewrote $links link(s) on $pages page(s) to use shortcodes.\n";
    57     }
    58
    59 }

[Raise a SilverStripe Framework issue/bug](https://github.com/silverstripe/silverstripe-framework/issues/new)
- [Raise a SilverStripe CMS issue/bug](https://github.com/silverstripe/silverstripe-cms/issues/new)
- Please use the Silverstripe Forums to ask development related questions. -