Tuesday, August 13, 2013

Using Canvas's API for global search and replace

So, this is a little outside my usual topics for blogging, but I always appreciate it when I find helpful code snippets online, so wanted to share this.

Today, I needed to go through 100 content pages in Instructure's Canvas LMS and make some search-and-replace type changes, but the kind that are best done using regular expressions.  I needed to rewrite image URLs, remove some links, etc.

So in case you ever need to do the same, here's the quick PHP script I threw together.  There is probably a more elegant way to do this, but I was in "get 'er done" mode :)

<?php
@set_time_limit(0); //make sure we don't timeout; this might take a while
ini_set("max_input_time", "2400");
ini_set("max_execution_time", "2400");
$courseid = 1; //your course ID
$token = 'your canvas access token';
$domain = 'yourdomain.instructure.com';
$cnt = 1;
while (1) {
//pull the pages listing. It's paginated, so keep pulling batches of 50 until we run out
$f = file_get_contents('https://'.$domain.'/api/v1/courses/'.$courseid.'/pages?per_page=50&page='.$cnt.'&access_token='.$token);
$cnt++;
if (trim($f)=='[]' || $cnt>20 ) {
break; //stop if we run out, or if something went wrong and $cnt is over 20
} else {
$pagelist = json_decode($f);
for ($i=0;$i<count($pagelist);$i++) {
$url = $pagelist[$i]->url; //grab page url from pages list
//pull the page json, decode it
$page = json_decode(file_get_contents('https://'.$domain.'/api/v1/courses/'.$courseid.'/pages/'.$url.'?access_token='.$token));
$str = $page->body; //grab the page html itself
//do your search and replaces here
//set up curl to use PUT to send the update page back
$ch = curl_init('https://'.$domain.'/api/v1/courses/'.$courseid.'/pages/'.$url.'?access_token='.$token);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, 'wiki_page[body]='.urlencode($str));
$response = curl_exec($ch);
if ($response===false) {
echo "fail on $url";
}
sleep(.5); //just so we don't hammer Canvas too quickly
}
}
}
echo "Done";
?>
view raw gistfile1.txt hosted with ❤ by GitHub

No comments:

Post a Comment